<?php
defined('BASEPATH') OR exit('No direct script access allowed');

// 新版班牌接口
class Brand_api extends BaseController {

	public function __construct() {
        parent::__construct();
    }

    // 获取离线缓存数据接口
    public function get_offline_data($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取本周课程列表
        $scheduleArray = $lessonArray = array();
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        foreach($scheduleList as $schedule) {
            $weekLesson = array();
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 判空
            if(!empty($scheduleSetting)){            
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {
                    foreach($scheduleSetting as $lessonTime) {
                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        $lsData['startTime'] = $lessonTime['beginTime'];
                        $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                        $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
    
                        $lessonKey = $i. $lsData['classIndex'];
                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            
            // 获取课程表课程
            $lessonParams['scheduleId'] = $schedule['id'];
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                if(isset($teacherList[$lesson['schedule_teacher']])) {
                    $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                    $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                    $weekLesson[$lessonKey]['teacherHeadimg'] = $teacherList[$lesson['schedule_teacher']]['headimgurl'];
                }          
                // 获取班级科目
                if(!in_array($classLesson, $lessonArray)) $lessonArray[] = $classLesson;
            }
            foreach($weekLesson as $key => &$value) {
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    if($scheduleLesson) {
                        $value['lessonName'] = '走班';
                        $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
                    }
                }
            }

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
            if($schedule['schedule_this_week']) {
                $scheduleArray = $weekLesson;
            }
        }
        // 获取本校全部班级
        $classParams['schoolId'] = $brandInfo['school_id'];
        $classParams['campusId'] = $brandInfo['campus_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取课程的考勤数据
        if(!empty($scheduleArray)) {
            foreach($scheduleArray as $key => $schedule) {
                if(!isset($schedule['id'])) {
                    continue;
                }
                $courseInfo = $this->classesModel->get_sch_lesson($schedule['id']);
                // $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
                if(isset($classList[$courseInfo['class_id']])) {
                    $classInfo = $classList[$courseInfo['class_id']];
                } else {
                    $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
                }
                // 获取学生考勤信息
                // $today = date("Y-m-d");
                // $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];
                // $studentList = $this->dataModel->get_sign_data($classInfo, $today, $isTeachingClass);

                $studentList = $this->dataModel->get_sign_data($classInfo, '', 0);
                // 检查用户签到情况
                $signArray = array(
                    "sign" => array(
                        'count' => 0,
                        'data' => array()
                    ),
                    "noSign" => array(
                        'count' => 0,
                        'data' => array()
                    )
                );
                foreach($studentList as $student) {
                    $studentData = array(
                        "id" => $student['sign_id'],
                        "studentId" => $student['id'],
                        "studentCard" => $student['realcard'],
                        "name" => $student['realname'],
                        "image" => $student['sign_img']. "!small",
                        "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                        "faceImage" => $student['face_image'],
                        "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg')
                    );
                    // 判断签到课程id是否等于当前课程id
                    if($student['sign_id'] && $student['course_id'] === $schedule['id']) {
                        $signArray['sign']['data'][] = $studentData;
                    } else {
                        $signArray['noSign']['data'][] = $studentData;
                    }
                }
                $signArray['sign']['count'] = count($signArray['sign']['data']);
                $signArray['noSign']['count'] = count($signArray['noSign']['data']);

                $scheduleArray[$key]['signData'] = $signArray;
            }
        }
        exit(json('', true, $scheduleArray));
    }

    // 获取离线缓存数据接口（暂用旧的）
    public function get_offline_data_new($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取本周课程列表
        $scheduleArray = $lessonArray = array();
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleParams['isThisWeek'] = 1;
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);
        foreach($scheduleList as $schedule) {
            $weekLesson = array();
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 判空
            if(!empty($scheduleSetting)){            
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {
                    foreach($scheduleSetting as $lessonTime) {
                        // 如未设置，默认为10
                        if(!isset($lessonTime['sign_interval'])) {
                            $lessonTime['sign_interval'] = 10;
                        }
                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        $lsData['startTime'] = $lessonTime['beginTime'];
                        $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                        // 新版上课时间
                        $lsData['startTimeNew'] = $lessonTime['beginTime'] . ':00';
                        $lsData['endTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                        // 考勤时间
                        if($lessonTime['sign_interval'] == 0) {
                            $lsData['signStartTime'] = '';
                            $lsData['signEndTime'] = '';
                        } else {
                            $lsData['signStartTime'] = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                            $lsData['signEndTime'] = date("H:i", strtotime($lessonTime['beginTime']) - 60) . ':59';
                        }

                        $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
    
                        $lessonKey = $i. $lsData['classIndex'];
                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            
            // 获取课程表课程
            $lessonParams['scheduleId'] = $schedule['id'];
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                if(isset($teacherList[$lesson['schedule_teacher']])) {
                    $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                    $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                    $weekLesson[$lessonKey]['teacherHeadimg'] = $teacherList[$lesson['schedule_teacher']]['headimgurl'];
                }          
                // 获取班级科目
                if(!in_array($classLesson, $lessonArray)) $lessonArray[] = $classLesson;
            }
            foreach($weekLesson as $key => &$value) {
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    if($scheduleLesson) {
                        $value['id'] = $scheduleLesson['id'];
                        $value['lessonName'] = '走班';
                        $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
                        // var_export($value);exit;
                        // 如进入考勤设置0，走班需固定上课前10分钟进入考勤模式
                        if(empty($value['signStartTime'])) {
                            $value['signStartTime'] = date("H:i", strtotime($value['startTime']) - 10 * 60) . ':00';
                            $value['signEndTime'] = date("H:i", strtotime($value['startTime']) - 60) . ':59';
                        }
                    }
                }
            }

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
            if($schedule['schedule_this_week']) {
                $scheduleArray = $weekLesson;
            }
        }
        // 获取本校全部班级
        $classParams['schoolId'] = $brandInfo['school_id'];
        $classParams['campusId'] = $brandInfo['campus_id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取课程的考勤数据
        if(!empty($scheduleArray)) {
            foreach($scheduleArray as $key => $schedule) {
                if(!isset($schedule['id'])) {
                    continue;
                }
                $courseInfo = $this->classesModel->get_sch_lesson($schedule['id']);
                // $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
                if(isset($classList[$courseInfo['class_id']])) {
                    $classInfo = $classList[$courseInfo['class_id']];
                } else {
                    $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
                }

                // 获取学生考勤信息
                $today = date("Y-m-d");
                $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];
                // $studentList = array();
                $studentList = $this->dataModel->get_sign_data($classInfo, $today, $isTeachingClass);

                // $studentList = $this->dataModel->get_sign_data($classInfo, '', 0);
                // 检查用户签到情况
                $signArray = array(
                    "sign" => array(
                        'count' => 0,
                        'data' => array()
                    ),
                    "noSign" => array(
                        'count' => 0,
                        'data' => array()
                    )
                );
                // var_export($scheduleSetting);exit;
                foreach($studentList as $student) {
                    $classIndex = $student['schedule_class_index'];
                    $refreshClassIndex = 0;
                    foreach($scheduleSetting as $settingKey => $time) {
                        if(isset($time['refresh']) && $time['refresh'] == '是' && $settingKey <= $classIndex - 1) {
                            $refreshClassIndex = $settingKey + 1;
                        }
                    }
                    // var_export($student);exit;
                    $studentData = array(
                        "id" => $student['sign_id'],
                        "studentId" => $student['id'],
                        "studentCard" => $student['realcard'],
                        "name" => $student['realname'],
                        "image" => $student['sign_img']. "!small",
                        "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                        "signTimeDetail" => $student['signTime'] ? $student['signTime'] : '',
                        "faceImage" => $student['face_image'],
                        "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                        "temperature" => $student['temperature'] ? $student['temperature'] : ''
                    );
                    // 判断离校
                    if($student['sign_id'] && $student['state'] != SIGN_STATE_LEAVE) {
                        // 判断签到是否在‘最近重新签到’后
                        if($student['schedule_class_index'] && $student['schedule_class_index'] >= $refreshClassIndex) {
                            $signArray['sign']['data'][] = $studentData;
                        } else {
                            $signArray['noSign']['data'][] = $studentData;
                        }
                    } else {
                        $signArray['noSign']['data'][] = $studentData;
                    }
                }
                $signArray['sign']['count'] = count($signArray['sign']['data']);
                $signArray['noSign']['count'] = count($signArray['noSign']['data']);
                    // var_export($signArray);exit;
                $scheduleArray[$key]['signData'] = $signArray;
            }
        }
        exit(json('', true, $scheduleArray));
    }

    // 获取班牌首页信息接口
    public function get_class_data($brandId = 0){

        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('configModel');
        $this->load->model('staffModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
        if($classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }

        // 获取班主任信息
        // $masterInfo = $this->schoolModel->get_teacher_info($classInfo['class_master']);
        $masterCoach = $this->staffModel->get_master_coach_by_class($classInfo['id']);
        if($masterCoach) {
            $masterInfo = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
        } else {
            $masterInfo = NULL;
        }
        // 获取班长信息
        $monitor = $this->schoolModel->get_monitor($brandInfo['class_id']);
        // 获取教师列表
        $teacherParams['schoolId'] = $classInfo['school_id'];
        // 过滤软删除
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        $scheduleArray = $lessonArray = array();
        $scheduleParams['schoolId'] = $classInfo['school_id'];
        $scheduleList = $this->classesModel->get_school_schedule($scheduleParams);

        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        // if(!$onlyOneSchedule) {
        //     // 转换date('w')获取的值为作息时间的week
        //     $this->load->helper('schedule');
        //     $week = transform__to_schedule_week(date('w'));
        //     // 获取当天的年级作息
        //     $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $week);
        //     if($gradeSchedule) {
        //         $scheduleList = array($gradeSchedule);
        //     } else {
        //         // 找不到年级作息
        //         $scheduleList = array($scheduleList[0]);
        //     }
        // }
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleList = array($mondayGradeSchedule);
            } else {
                $scheduleList = array($scheduleList[0]);
            }
        }

        // var_export($scheduleList);exit;

        foreach($scheduleList as $schedule) {
            $weekLesson = array();
            $scheduleSetting = json_decode($schedule['schedule_time_json'], true);
            // 判空
            if(!empty($scheduleSetting)){
                $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                // 生成全部课程时间点
                for($i = 1; $i <= $schedule['schedule_week_days']; $i ++) {

                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    if(!$onlyOneSchedule) {
                        // 获取当天的年级作息
                        $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                        if($gradeSchedule) {
                            $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                        }
                    }

                    foreach($scheduleSetting as $lessonTime) {
                        $lsData['weekIndex'] = $i;
                        $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                        // 旧版上课时间
                        $lsData['startTime'] = $lessonTime['beginTime'];
                        $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                        // 新版上课时间
                        $lsData['startTimeNew'] = $lessonTime['beginTime'] . ':00';
                        $lsData['endTimeNew'] = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                        if(!isset($lessonTime['sign_interval'])) {
                            // 如未设置，默认为10
                            $lessonTime['sign_interval'] = 10;
                        }
                        // 考勤时间
                        if($lessonTime['sign_interval'] == 0) {
                            $lsData['signStartTime'] = '';
                            $lsData['signEndTime'] = '';
                        } else {
                            $lsData['signStartTime'] = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                            // 添加0-10秒偏移量
                            $lsData['signStartTime'] = date("H:i:s", strtotime($lsData['signStartTime']) + rand(0, 10));

                            $lsData['signEndTime'] = date("H:i", strtotime($lessonTime['beginTime']) - 60) . ':59';
                        }

                        $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = $lsData['teacherHeadimg'] = '';
    
                        $lessonKey = $i. $lsData['classIndex'];

                        // // 返回sign_interval，供走班情况判断
                        $lsData['sign_interval'] = $lessonTime['sign_interval'];

                        $weekLesson[$lessonKey] = $lsData;
                    }
                }
            }
            // 获取课程表课程
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            // 年级不同作息，不需要传schedule_id
            if($onlyOneSchedule) {
                $lessonParams['scheduleId'] = $schedule['id'];
            }
            $lessonParams['classId'] = $classInfo['id'];
            $lessonParams['classroom'] = $classInfo['classroom_id'];
            $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
                        // var_export($lessonList);exit;
            foreach($lessonList as $lesson) {
                $classLesson = $lesson['schedule_lesson'];
                // 写入课程名称
                $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
                $weekLesson[$lessonKey]['id'] = $lesson['id'];
                $weekLesson[$lessonKey]['lessonName'] = $classLesson;
                if(isset($teacherList[$lesson['schedule_teacher']])) {
                    $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                    $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
                    $weekLesson[$lessonKey]['teacherHeadimg'] = $teacherList[$lesson['schedule_teacher']]['headimgurl']; 
                }
                // 获取班级科目
                if(!in_array($classLesson, $lessonArray)) $lessonArray[] = $classLesson;
            }

            foreach($weekLesson as $key => &$value) {
                // 过滤已删除
                if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                    unset($weekLesson[$key]);
                    continue;
                }
                if(empty($value['lessonName'])) {
                    // 判断是否走班
                    $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                    // 年级不同作息，不需要传schedule_id
                    if(!$onlyOneSchedule) {
                        $scheduleLesson = $this->classesModel->get_schedule_lesson_info_for_grade($value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
                    }

                    if($scheduleLesson) {
                        $value['id'] = $scheduleLesson['id'];
                        $value['lessonName'] = '走班';
                        $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
                        // var_export($value);exit;
                        // 如进入考勤设置0，走班需固定上课前10分钟进入考勤模式
                        if(empty($value['signStartTime'])) {
                            $value['signStartTime'] = date("H:i", strtotime($value['startTime']) - 10 * 60) . ':00';
                            // 添加0-10秒偏移量
                            $value['signStartTime'] = date("H:i:s", strtotime($value['signStartTime']) + rand(0, 10));

                            $value['signEndTime'] = date("H:i", strtotime($value['startTime']) - 60) . ':59';
                        }
                    }
                }
            }

            // 检查是本周还是下周课程
            $weekLesson = array_values($weekLesson);
            if($schedule['schedule_this_week']) {
                $scheduleArray['week_lesson'] = $weekLesson;
            }
        }

        // 课时数组
        $scheduleArray['period'] = array();
        if($scheduleList[0]) {
            $earlyMorningNum = $scheduleList[0]['schedule_early_morning_number'];
            $nightNum = $scheduleList[0]['schedule_night_number'];
            $lessonNum = $scheduleList[0]['schedule_morning_number'] + $scheduleList[0]['schedule_afternoon_number'];
            for($i = 1; $i <= $earlyMorningNum; $i ++) {
                $scheduleArray['period'][] = '';
            }
            for($i = 1; $i <= $lessonNum; $i ++) {
                $scheduleArray['period'][] = $i;
            }
            for($i = 1; $i <= $nightNum; $i ++) {
                $scheduleArray['period'][] = '';
            }
        }
        

        // 班级相册，首页推荐
        $albumParams['classId'] = $classInfo['id'];
        $albumParams['recommend'] = 1;
        $albumList = $this->contentModel->get_album($albumParams);
        $albumArray = array();
        foreach($albumList as $image) {
            $albumArray[] = array(
                "imageLink" => $image['image_link'],
                "imageDesc" => $image['image_desc']
            );
        }
        // 获取天气预报编码
        $areaInfo = $this->schoolModel->get_area_info($schoolInfo['school_area']);
        $cityJson = file_get_contents(APPLICATION_FOLDER. DIRECTORY_SEPARATOR . "data". DIRECTORY_SEPARATOR. "_city.json");
        $cityData = array_value_to_key(json_decode($cityJson, true), 'city_name');
        $weatherId = isset($cityData[$areaInfo['area_name']]) ? $cityData[$areaInfo['area_name']]['city_code'] : 0;
        // 获取前10条班级通知
        $notifyParams['isDelete'] = 0;
        $notifyParams['classId'] = $brandInfo['class_id'];
        $notifyParams['pageStart'] = 0;
        $notifyParams['pageSize'] = 10;
        $notifyParams['field'] = 'id, notify_title as title, notify_content as content, updatetime as time, notify_type, external_link, notify_urgent, urgent_endtime, is_top';
        $notifyParams['orderByFirst'] = array('order' => 'is_top', 'sort' =>'DESC');
        $notifyParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $notifys = $this->contentModel->get_notify_list($notifyParams);
        // 获取前10条班级动态
        $newsParams['isDelete'] = 0;
        $newsParams['classId'] = $brandInfo['class_id'];
        $newsParams['pageStart'] = 0;
        $newsParams['pageSize'] = 10;
        $newsParams['field'] = 'id, news_title as title, updatetime as time';
        $newsParams['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $news = $this->contentModel->get_news_list($newsParams);

        // 返回值
        $ret['className'] = $classInfo['class_name'];
        $ret['classImg'] = $classInfo['class_logo'] ? $classInfo['class_logo'] : get_sys_img('class.jpg');

        // 班级格言
        $ret['classSlogan'] = $classInfo['class_slogan'] ? $classInfo['class_slogan'] : '';
        // 班级口号
        $ret['classWord'] = $classInfo['class_word'] ? $classInfo['class_word'] : '';
        $ret['classContent'] = trim_link_tags($classInfo['class_content']);
        $ret['weatherId'] = $weatherId;
        // 班主任
        $ret['classMaster'] = (object)null;;
        if(!empty($masterInfo)){
            $ret['classMaster'] = array(
                "id" => $masterInfo['id'],
                "name" => $masterInfo['realname'],
                "headimgurl" => $masterInfo['headimgurl'],
                "mobile" => $masterInfo['mobile'],
                "message" => $masterInfo['content']
            );
        }
        // 班长
        $ret['monitor'] = (object)null;
        if(!empty($monitor)) {
            $ret['monitor'] = $monitor;
        }
        // 班级课程
        $ret['classLesson'] = $lessonArray;
        // 首页推荐图片
        $ret['albumList'] = $albumArray;
        // 课程信息
        $ret['schedule'] = $scheduleArray ? $scheduleArray : (object)null;
        // 本月之星
        $ret['classStar'] = '';
        if (null !== $classInfo['class_star']) {
            $student = $this->schoolModel->get_student_info($classInfo['class_star']);
            if (isset($student['realname'])) {
                $ret['classStar'] = $student['realname'];
            } 
        }      
        // 班牌管理密码
        $ret['brandPassword'] = $brandInfo['brand_password'];
        // 班牌开关机时间
        $ret['brandPowerTime'] = json_decode($brandInfo['power_time'], true);
        // 是否启用人脸识别功能
        $ret['brandFaceDetect'] = intval($schoolInfo['school_face_detect']);
        // // 是否启用招考查询功能
        // $ret['brandExamQuery'] = intval($schoolInfo['school_exam_query']);
        // 是否启用考务功能
        $ret['brandExam'] = intval($schoolInfo['school_exam']);
        // // 是否启用智学网
        // $ret['zhi_xue'] = empty($schoolInfo['school_zhi_xue']) ? '' : 'https://www.zhixue.com/wap_login.html?from=&channel=00';
		// 相机缩放倍数
        $ret['cameraZoom'] = floatval($brandInfo['brand_camera_zoom']);
        // 班牌主题
        $ret['theme'] = $schoolInfo['brand_theme'];
        // 班牌上课前多久进入考勤模式，0为关闭该模式
        $ret['sign_interval'] = $brandInfo['sign_interval'];
        // 校训
        $ret['school_motto'] = $schoolInfo['school_motto'];
        // 班徽
        $ret['class_logo'] = $classInfo['class_logo'] ? $classInfo['class_logo'] : get_sys_img('class.jpg');
        // 前10条班级通知
        $ret['notifys'] = array();
        if(!empty($notifys)) {
            foreach($notifys as $key => $notify) {
                $notifys[$key]['content'] = urlencode($notify['content']);
                // 是否置顶
                $notifys[$key]['is_top'] = $notifys[$key]['is_top'] ? true : false;
            }
            $ret['notifys'] = $notifys;
        }
        // 前10条动态
        $ret['news'] = array();
        if(!empty($news)) {
            $ret['news'] = $news;
        }

        // 招考查询改成外链
        // // 获取招考查询地址
        // $examQueryLink = '';
        // $link = $this->configModel->get_config_info('exam_query_link', true);
        // if(!empty($link)){
        //     $examQueryLink = $link;
        // }
        // $ret['exam_query_link'] = $examQueryLink;
        // 班牌开关机时间（新逻辑）
        $week = $this->configModel->get_school_campus_config($schoolInfo['id'], $classInfo['campus_id'], 'power_week');
        $holiday = $this->configModel->get_school_campus_config($schoolInfo['id'], $classInfo['campus_id'], 'power_holiday');
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            sort($weekArr);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        if($holiday && isset($holiday['config_value'])) {
            $holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $holidayArr = array();
        }
        $ret['brandPowerTimeNew'] = array(
            'time' => json_decode($brandInfo['power_time'], true),
            'week' => $weekArr,
            'holiday' => $holidayArr
        );
        // 是否来自
        $ret['schoolFrom'] = $schoolInfo['school_from'];
        // 对话留言内容发送
        $ret['allow_send'] = $brandInfo['allow_send'];
        $ret['school_id'] = $brandInfo['school_id'];

        // 定时开关机计算好的时间v2
        $brandPowerTimeV2 = $this->_get_power_time_v2($brandInfo['power_time_v2'], $holiday['config_value']);
        if($brandPowerTimeV2['startupTime']){
            // 添加0-5分钟偏移量
            $brandPowerTimeV2['startupTime'] = date("Y-m-d H:i:s", strtotime($brandPowerTimeV2['startupTime']) + rand(0, 5) * 60);
        }
        $ret['brandPowerTimeV2'] = $brandPowerTimeV2;
        // 定时开关机配置v2
        $ret['brandPowerTimeArrV2'] = array(
            'holiday' => $holidayArr,
            'weekTime' => json_decode($brandInfo['power_time_v2'], true),
        );
        // 校训
        $ret['faceSimilar'] = $schoolInfo['face_similar'];
        // var_export($ret['brandPowerTimeV2']);exit;

        // 智能门锁
        // $smartLockConfigValueArr = (object)null;
        // if(isset($schoolInfo['school_smart_lock']) && $schoolInfo['school_smart_lock'] == 1) {
        //     // 获取门锁配置
        //     $smartLockConfig = $this->configModel->get_school_campus_config($schoolInfo['id'], $brandInfo['campus_id'], 'school_smart_lock');
        //     if($smartLockConfig['config_value']) {
        //         $smartLockConfigValueArr = json_decode($smartLockConfig['config_value'], true); 
        //     }         
        // }
        // $ret['smartLock'] = array(
        //     'isEnable' => isset($schoolInfo['school_smart_lock']) ? $schoolInfo['school_smart_lock'] : 0,
        //     'value' => $smartLockConfigValueArr
        // );
        $ret['smartLock'] = isset($schoolInfo['school_smart_lock']) ? $schoolInfo['school_smart_lock'] : 0;
        // 虹软SDK版本
        $ret['isFreeFaceSdk'] = $schoolInfo['is_free_face_sdk'] ? true : false;

        // 班级主题
        $subjectContent = (object)null;
        $subjectContentTemp = (object)null;
        $subjectContentParams['schoolId'] = $brandInfo['school_id'];
        $subjectContentParams['campusId'] = $brandInfo['campus_id'];
        $subjectContentParams['classId'] = $brandInfo['class_id'];
        // 生效的
        $subjectContentParams['effective'] = 1;
        // 过滤软删除
        $subjectContentParams['isDelete'] = 0;
        $subjectContentParams['field'] = 'type, title, content, videos, play_in_class_mode, endtime';
        $subjectContentList = $this->contentModel->get_subject_content_list($subjectContentParams);

        if($subjectContentList) {
            $subjectContent = $subjectContentList[0];
            $subjectContentTemp = array();
            $subjectContentTemp['type'] = (int) $subjectContent['type'];
            $subjectContentTemp['title'] = $subjectContent['title'];
            $subjectContentTemp['content'] = $subjectContent['content'];
            $subjectContentTemp['playInClassMode'] = $subjectContent['play_in_class_mode'] ? true : false;
            $subjectContentTemp['endtime'] = $subjectContent['endtime'] . ':59';
            if($subjectContent['type'] == SUBJECT_CONTENT_TYPE_VIDEO && !empty($subjectContent['videos'])) {
                $videos = json_decode($subjectContent['videos'], true);
                foreach($videos as &$video) {
                    unset($video['old_link']);
                }
                $subjectContentTemp['videos'] = $videos;
            } else {
                $subjectContentTemp['videos'] = array();
            }
        }
       
        $ret['subjectContent'] = $subjectContentTemp;
        
        exit(json("", true, $ret));
    }

    // 获取班级通知列表
    public function get_class_unread_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        $this->load->model('configModel');
        $this->load->model('staffModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info_include_delete($brandInfo['class_id']);
        if($classInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取学校信息
        $schoolInfo = $this->schoolModel->get_school_info($classInfo['school_id']);
        if($schoolInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }
        // 获取年级信息
        $gradeInfo = $this->classesModel->get_grade_info($classInfo['grade_id']);
        if($gradeInfo['is_delete'] == 1) {
            exit(json("无效的班牌id", false));
        }

        // 获取班级学生人数
        $studentParams['classId'] = $classInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        $unreadStudentArr = array();
        foreach($studentList as $key => $student) {
            $noteList = $this->wxUserModel->get_user_wx_note_list($student['id'], BIND_TYPE_STUDENT, 1);
            if($noteList) {
                $filterdNoteList = array();
                $unreadArr = array();
                foreach($noteList as $note) {
                    if($note['send_user_id'] === $note['receive_user_id']) {
                        // 家长留言
                        $otherUserId = 964;
                        // 计算未读数
                        if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['is_parent'] == 1) {
                            if(isset($unreadArr[$otherUserId])) {
                                $unreadArr[$otherUserId] ++;
                            } else {
                                $unreadArr[$otherUserId] = 1;
                            }
                        }
                    } else {
                        // 教师留言
                        if($note['send_user_type'] == BIND_TYPE_TEACHER) {
                            $otherUserId = $note['send_user_id'];
                        } else {
                            $otherUserId = $note['receive_user_id'];
                        }
                        // 计算未读数
                        if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['send_user_type'] == BIND_TYPE_TEACHER) {
                            if(isset($unreadArr[$otherUserId])) {
                                $unreadArr[$otherUserId] ++;
                            } else {
                                $unreadArr[$otherUserId] = 1;
                            }
                        }
                    }
                    if(!isset($filterdNoteList[$otherUserId])) {
                        $filterdNoteList[$otherUserId] = $note; 
                    }
                }
                $unreadCount = 0;
                if($filterdNoteList) {
                    foreach($filterdNoteList as $key => $value) {
                        $unread = isset($unreadArr[$key]) ? $unreadArr[$key] : 0;
                        $unreadCount += $unread;
                    }
                }
                if($unreadCount > 0) {
                    array_push($unreadStudentArr, array(
                        'student_id' => $student['id'],
                        'realname' => $student['realname'],
                        'unread_count' => $unreadCount
                    ));

                }
            }
        }

        exit(json("", true, $unreadStudentArr));
    }

     // 获取学生考勤信息接口（已废弃）
     public function get_student_sign_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("无效的班牌id");

        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']); 
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("无效的课程id");
        // 获取学生考勤信息
        $today = date("Y-m-d");
        $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];
        $studentList = $this->dataModel->get_sign_data($classInfo, $today, $isTeachingClass, $courseId);
        // var_export($studentList);exit;
        // 检查用户签到情况
        $signArray = array(
            "sign" => array(
                'count' => 0,
                'data' => array()
            ),
            "noSign" => array(
                'count' => 0,
                'data' => array()
            ),
            // 还不支持请假功能
            // "leave" => array()
        );
        foreach($studentList as $student) {
            $studentData = array(
                "id" => $student['sign_id'],
                "studentId" => $student['id'],
                "studentCard" => $student['realcard'],
                "name" => $student['realname'],
                "image" => $student['sign_img']. "!small",
                "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                "signTimeDetail" => $student['signTime'] ? $student['signTime'] : '',
                "faceImage" => $student['face_image'],
                "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                "temperature" => $student['temperature'] ? $student['temperature'] : ''
            );

            if($student['sign_id']) {
                $signArray['sign']['data'][] = $studentData;
            } else {
                $signArray['noSign']['data'][] = $studentData;
            }
        }
        $signArray['sign']['count'] = count($signArray['sign']['data']);
        $signArray['noSign']['count'] = count($signArray['noSign']['data']);
        exit(json("", true, $signArray));
    }

    // 备份（将来获取课程考勤sql拆成不连表查询）
    // // 获取学生考勤信息接口（版本2）
    // public function get_student_sign_data_v2($brandId){
    //     // 加载数据库类
    //     $this->load->model('classesModel');
    //     $this->load->model('dataModel');
    //     $this->load->model('schoolModel');
    //     // 获取班牌信息
    //     $brandInfo = $this->classesModel->get_brand_info($brandId);
    //     if(!$brandInfo) throw new Exception("无效的班牌id");

    //     // 如果有传课程ID，则根据当前课程获取班级信息
    //     $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
    //     if($courseId) {
    //         $courseInfo = $this->classesModel->get_sch_lesson($courseId);
    //         $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
    //         // echo'<pre>';var_export($refreshClassIndex);exit;
    //     } else {
    //         // 获取班级信息
    //         $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
    //     }
    //     if(!$classInfo) throw new Exception("无效的课程id");
    //     // 获取之前最近的重新签到课程，包含本节课
    //     $schduleParams['schoolId'] = $brandInfo['school_id'];
    //     $schduleParams['campusId'] = $brandInfo['campus_id'];
    //     $schduleParams['isThisWeek'] = 1;
    //     $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
    //     $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
   
    //     $classIndex = 1;
    //     if($courseId) {
    //         $classIndex = $courseInfo['schedule_class_index'];
    //     } else {
    //         // 菜单查看班级考勤，传当前时间：时分秒
    //         if(empty($this->get('time'))) {
    //             throw new Exception("参数不能为空");
    //         }
    //         $time = $this->get('time');
    //         if(!preg_match("/\d{2}:\d{2}:\d{2}/", $time)) {
    //             throw new Exception("参数格式不正确");
    //         }
    //         // var_export($timeArr);exit;
    //         foreach($timeArr as $lessonKey => $lessonTime) {  
    //             // 如未设置，默认为10
    //             if(!isset($lessonTime['sign_interval'])) {
    //                 $lessonTime['sign_interval'] = 10;
    //             }

    //             // 课程结束时间
    //             // $endTime = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
    //             // $startTime = $lessonTime['beginTime'] . ':00';
    //             $signStartTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
    //             // 小于第一节情况
    //             if($lessonKey == 0) {
    //                 if($time <= $signStartTime) {
    //                     $classIndex = $lessonTime['timeslotInDay'];
    //                     break;
    //                 }
    //             }
    //             // 大于最后一节情况
    //             if($lessonKey == count($timeArr) - 1) {
    //                 if($time >= $signStartTime) {
    //                     $classIndex = $lessonTime['timeslotInDay'];
    //                     break;
    //                 }
    //             }
    //             // 其他情况
    //             if($lessonKey < count($timeArr) - 1) {
    //                 if(!isset($timeArr[$lessonKey + 1]['sign_interval'])) {
    //                     $timeArr[$lessonKey + 1]['sign_interval'] = 10;
    //                 }
    //                 // 下节课考勤开始时间
    //                 $nextSignStartTime = date("H:i", strtotime($timeArr[$lessonKey + 1]['beginTime']) - ($timeArr[$lessonKey + 1]['sign_interval']) * 60) . ':00';
    //                 // 大于等于当前考勤开始时间，小于下节考勤开始时间
    //                 if($time >= $signStartTime && $time < $nextSignStartTime) {
    //                     $classIndex = $lessonTime['timeslotInDay'];
    //                     break;
    //                 }
    //             }
    //         }      
    //         // var_export($classIndex);exit;
    //     }

    //     $refreshClassIndex = 0;
    //     foreach($timeArr as $key => $time) {
    //         if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
    //             $refreshClassIndex = $key + 1;
    //         }
    //     }
    //     // 获取学生考勤信息
    //     $today = date("Y-m-d");
    //     $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];

    //     // 学生列表
    //     $stuParams['isDelete'] = 0;
    //     $stuParams['classORteach'] = $classInfo['id'];
    //     $stuParams['schoolId'] = $brandInfo['school_id'];
    //     $studentList = $this->schoolModel->get_student_list($stuParams);
    //     // 考勤列表
    //     $signList = $this->dataModel->get_sign_data_fast($classInfo, $today, $isTeachingClass, $courseId, '', $brandInfo['school_id']);
    //     // 以student_id作为键值
    //     $signList = array_value_to_key($signList, 'student_id');
    //     // echo '<pre>';var_export($signList);exit;
    //     // 检查用户签到情况
    //     $signArray = array(
    //         "sign" => array(
    //             'count' => 0,
    //             'data' => array()
    //         ),
    //         "noSign" => array(
    //             'count' => 0,
    //             'data' => array()
    //         ),
    //         // 还不支持请假功能
    //         // "leave" => array()
    //     );

    //     // 临时课程数据
    //     $tempCourseArr = array();
    //     foreach($studentList as $student) {
    //         $studentData = array(
    //             "id" => '',
    //             "studentId" => $student['id'],
    //             "studentCard" => $student['realcard'],
    //             "name" => $student['realname'],
    //             "faceImage" => $student['face_image'],
    //             "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
    //             'course_id' => '',
    //             "image" => '',
    //             "signTime" => '',
    //             "signTimeDetail" => '',
    //             "temperature" => '',
    //             'state' => ''
    //         );
    //         if(isset($signList[$student['id']])) {
    //             $signTemp = $signList[$student['id']];
    //             $studentData['id'] = $signTemp['id'];
    //             $studentData['course_id'] = $signTemp['course_id'];
    //             $studentData['image'] = $signTemp['sign_img'];
    //             $studentData['signTime'] = date("H时i分", strtotime($signTemp['createtime']));
    //             $studentData['signTimeDetail'] = $signTemp['createtime'];
    //             $studentData['temperature'] = $signTemp['temperature'];
    //             $studentData['state'] = $signTemp['state'];
    //         }

    //         // 判断离校
    //         if($studentData['id'] && $studentData['state'] != SIGN_STATE_LEAVE) {
    //             // 查询临时数组是否有class_index数据
    //             // 如果有则读取临时数组
    //             // 如果没有，则查询数据库。将查询数据保存到临时数组
    //             $scheduleClassIndex = 0;
    //             if($studentData['course_id']) {
    //                 if(isset($tempCourseArr[$studentData['course_id']])) {
    //                     $scheduleClassIndex = $tempCourseArr[$studentData['course_id']];
    //                 } else {
    //                     $courseInfo = $this->dataModel->get_school_schedule_lesson($studentData['course_id']);
    //                 }
    //                 if($courseInfo) {
    //                     $scheduleClassIndex = $courseInfo['schedule_class_index'];
    //                     $tempCourseArr[$courseInfo['id']] = $scheduleClassIndex;
    //                 }
    //             }

    //             // 判断签到是否在‘最近重新签到’后
    //             if($scheduleClassIndex && $scheduleClassIndex >= $refreshClassIndex) {
    //                 $signArray['sign']['data'][] = $studentData;
    //             } else {
    //                 $studentData['id'] = '';
    //                 $studentData['image'] = '';
    //                 $signArray['noSign']['data'][] = $studentData;
    //             }
    //         } else {
    //             $studentData['id'] = '';
    //             $studentData['image'] = '';
    //             $signArray['noSign']['data'][] = $studentData;
    //         }
    //     }
    //     $signArray['sign']['count'] = count($signArray['sign']['data']);
    //     $signArray['noSign']['count'] = count($signArray['noSign']['data']);
    //     exit(json("", true, $signArray));
    // }

    // 备份201118
    // 获取学生考勤信息接口（版本2）
    public function get_student_sign_data_v2($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("无效的班牌id");

        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
            // echo'<pre>';var_export($refreshClassIndex);exit;
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("无效的课程id");
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $brandInfo['school_id'];
        $schduleParams['campusId'] = $brandInfo['campus_id'];
        $schduleParams['isThisWeek'] = 1;
        // 兼容不同年级作息
        $schduleParams['gradeId'] = $classInfo['grade_id'];
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        if(empty($timeArr)) {
            $timeArr = array();
        } 
        $classIndex = 1;
        if($courseId) {
            $classIndex = $courseInfo['schedule_class_index'];
        } else {
            // 菜单查看班级考勤，传当前时间：时分秒
            if(empty($this->get('time'))) {
                throw new Exception("参数不能为空");
            }
            $time = $this->get('time');
            if(!preg_match("/\d{2}:\d{2}:\d{2}/", $time)) {
                throw new Exception("参数格式不正确");
            }
            // var_export($timeArr);exit;
            foreach($timeArr as $lessonKey => $lessonTime) {  
                // 如未设置，默认为10
                if(!isset($lessonTime['sign_interval'])) {
                    $lessonTime['sign_interval'] = 10;
                }

                // 课程结束时间
                // $endTime = date("H:i", strtotime($lessonTime['beginTime']) + ($lessonTime['duration'] - 1) * 60) . ':59';
                // $startTime = $lessonTime['beginTime'] . ':00';
                $signStartTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
                // 小于第一节情况
                if($lessonKey == 0) {
                    if($time <= $signStartTime) {
                        $classIndex = $lessonTime['timeslotInDay'];
                        break;
                    }
                }
                // 大于最后一节情况
                if($lessonKey == count($timeArr) - 1) {
                    if($time >= $signStartTime) {
                        $classIndex = $lessonTime['timeslotInDay'];
                        break;
                    }
                }
                // 其他情况
                if($lessonKey < count($timeArr) - 1) {
                    if(!isset($timeArr[$lessonKey + 1]['sign_interval'])) {
                        $timeArr[$lessonKey + 1]['sign_interval'] = 10;
                    }
                    // 下节课考勤开始时间
                    $nextSignStartTime = date("H:i", strtotime($timeArr[$lessonKey + 1]['beginTime']) - ($timeArr[$lessonKey + 1]['sign_interval']) * 60) . ':00';
                    // 大于等于当前考勤开始时间，小于下节考勤开始时间
                    if($time >= $signStartTime && $time < $nextSignStartTime) {
                        $classIndex = $lessonTime['timeslotInDay'];
                        break;
                    }
                }
            }      
            // var_export($classIndex);exit;
        }

        $refreshClassIndex = 0;
        foreach($timeArr as $key => $time) {
            if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
                $refreshClassIndex = $key + 1;
            }
        }
        // 获取学生考勤信息
        $today = date("Y-m-d");
        $isTeachingClass = $classInfo['id'] != $brandInfo['class_id'];

        $studentList = $this->dataModel->get_sign_data_fast($classInfo, $today, $isTeachingClass, $courseId, '', $brandInfo['school_id']);
        // echo '<pre>';var_export($studentList);exit;
        // 检查用户签到情况
        $signArray = array(
            "sign" => array(
                'count' => 0,
                'data' => array()
            ),
            "noSign" => array(
                'count' => 0,
                'data' => array()
            ),
            // 还不支持请假功能
            // "leave" => array()
        );

        // 临时课程数据
        $tempCourseArr = array();
        foreach($studentList as $student) {
            $studentData = array(
                "id" => $student['sign_id'],
                "studentId" => $student['id'],
                "studentCard" => $student['realcard'],
                "name" => $student['realname'],
                "image" => $student['sign_img']. "!small",
                "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                "signTimeDetail" => $student['signTime'] ? $student['signTime'] : '',
                "faceImage" => $student['face_image'],
                "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                "temperature" => $student['temperature'] ? $student['temperature'] : ''
            );

            // 判断离校
            if($student['sign_id'] && $student['state'] != SIGN_STATE_LEAVE) {
                // 查询临时数组是否有class_index数据
                // 如果有则读取临时数组
                // 如果没有，则查询数据库。将查询数据保存到临时数组
                $scheduleClassIndex = 0;
                if($student['course_id']) {
                    if(isset($tempCourseArr[$student['course_id']])) {
                        $scheduleClassIndex = $tempCourseArr[$student['course_id']];
                    } else {
                        $courseInfo = $this->dataModel->get_school_schedule_lesson($student['course_id']);
                    }
                    if($courseInfo) {
                        $scheduleClassIndex = $courseInfo['schedule_class_index'];
                        $tempCourseArr[$courseInfo['id']] = $scheduleClassIndex;
                    }
                }

                // 判断签到是否在‘最近重新签到’后
                if($scheduleClassIndex && $scheduleClassIndex >= $refreshClassIndex) {
                    $signArray['sign']['data'][] = $studentData;
                } else {
                    $studentData['id'] = '';
                    $studentData['image'] = '';
                    $signArray['noSign']['data'][] = $studentData;
                }
            } else {
                $studentData['id'] = '';
                $studentData['image'] = '';
                $signArray['noSign']['data'][] = $studentData;
            }
        }
        $signArray['sign']['count'] = count($signArray['sign']['data']);
        $signArray['noSign']['count'] = count($signArray['noSign']['data']);
        exit(json("", true, $signArray));
    }

    // 获取班级通知列表
    public function get_class_notify_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("无效的班牌id");
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(empty($classInfo)) throw new Exception("无效的班牌id");
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_notify_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $data['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $notifyData = array();
        $notifyList = $this->contentModel->get_notify_list($data);
        foreach($notifyList as $notify) {
            if($notify['imgs']) {
                $imgArr = explode(',', $notify['imgs']);
            } else {
                $imgArr = array();
            }
            $notifyData[] = array(
                "id" => $notify['id'],
                "title" => $notify['notify_title'],
                "content" => urlencode($notify['notify_content']),
                "time" => $notify['createtime'],
                "updatetime" => $notify['updatetime'],
                'img_arr' => $imgArr,
                'notify_type' => $notify['notify_type'],
                'external_link' => $notify['external_link'],
                'notify_urgent' => $notify['notify_urgent'],
                'urgent_endtime' => $notify['urgent_endtime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $notifyData;
        exit(json("", true, $ret));
    }

    // 获取班级通知详情
    public function get_class_notify_info($brandId, $notifyId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));

        // 获取通知详情
        $notifyInfo = $this->contentModel->get_notify_info($notifyId);
        if(!$notifyInfo) throw new Exception("内容不存在");
        // 返回值
        $ret['id'] = $notifyInfo['id'];
        $ret['title'] = $notifyInfo['notify_title'];
        $ret['content'] = trim_link_tags(urlencode($notifyInfo['notify_content']));
        $ret['time'] = substr($notifyInfo['updatetime'], 0, 16);
        $ret['notify_urgent'] = $notifyInfo['notify_urgent'];
        $ret['endtime'] = $notifyInfo['urgent_endtime'];
        if($notifyInfo['imgs']) {
            $imgArr = explode(',', $notifyInfo['imgs']);
        } else {
            $imgArr = array();
        }
        $ret['img_arr'] = $imgArr;
        $ret['notify_type'] = $notifyInfo['notify_type'];
        $ret['external_link'] = $notifyInfo['external_link'];
        exit(json("", true, $ret));
    }

    // 获取班级动态列表
    public function get_class_news_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(empty($classInfo)) throw new Exception("无效的班牌id");
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['isCron'] = 0;
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_news_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['isCron'] = 0;
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $data['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');  
        $newsData = array();
        $newsList = $this->contentModel->get_news_list($data);
        $imgArr = array();
        foreach($newsList as $key => $news) {
            if($news['imgs']) {
                $imgArr = explode(',', $news['imgs']);
            } else {
                $imgArr = array();
            }
            if($news['videos']) {
                $videoArr = json_decode($news['videos'], JSON_UNESCAPED_UNICODE);
                // // 加载又拍云sdk
                // require_once('vendor/autoload.php');
                // // 初始化又拍云接口
                // $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
                // $upyun = new Upyun\Upyun($config);
                // // 判断视频压缩是否完成
                // foreach($videoArr as &$video) {
                //      // 返回false即视频不存在
                //     if($key == 0) {
                //         // 判断最新一条视频是否压缩完成
                //         $linkUpyun = str_replace(UP_URL, '', $video['link']);
                //         if(!$upyun->has($linkUpyun)) {
                //             $video['link'] =  isset($video['old_link']) ? $video['old_link'] : '';
                //         }
                //     }

                //     unset($video['old_link']);
                // }
            } else {
                $videoArr = array();
            }
            // 过滤掉空视频
            foreach($videoArr as $key => $value) {
                if($value['link'] == '') {
                    unset($videoArr[$key]);
                }
            }
            if($news['audios']) {
                $audioArr = json_decode($news['audios'], JSON_UNESCAPED_UNICODE);
            } else {
                $audioArr = array();
            }

            if($imgArr) {
                $cover = $imgArr[0];
            } else {
                $cover = get_img_link_from_text($news['news_content']);
            }
            $newsData[] = array(
                "id" => $news['id'],
                "cover" => $cover,
                "title" => $news['news_title'],
                "content" => trim_link_tags(urlencode($news['news_content'])),
                "time" => $news['createtime'],
                "updatetime" => $news['updatetime'],
                'img_arr' => $imgArr,
                // 'video_cover' => $news['video_cover'],
                // 'video_link' => $news['video_link'],
                'video_arr' => $videoArr,
                'audio_arr' => $audioArr
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $newsData;
        exit(json("", true, $ret));
    }

    // 获取校园公告列表
    public function get_class_announce_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(empty($classInfo)) throw new Exception("无效的班牌id");
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['schoolId'] = $classInfo['school_id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_announce_list($totalParams);
        // 获取数据
        $data['isDelete'] = 0;
        $data['schoolId'] = $classInfo['school_id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $data['orderBy'] = array('order' => 'updatetime', 'sort' =>'DESC');
        $announceData = array();
        $announceList = $this->contentModel->get_announce_list($data);
        foreach($announceList as $announce) {
            $announceData[] = array(
                "id" => $announce['id'],
                "title" => $announce['announce_title'],
                "content" => urlencode($announce['announce_content']),
                'announce_type' => $announce['announce_type'],
                'external_link' => $announce['external_link'],
                "time" => $announce['createtime'],
                "updatetime" => $announce['updatetime']
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $announceData;
        exit(json("", true, $ret));
    }

    // 获取班级作业列表
    public function get_class_homework_data($brandId, $page = 1){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取日期请求参数
        if(!empty($this->get('date'))) {
            $totalParams['date'] = $this->get('date');
            $data['date'] = $this->get('date');
        }
        // 获取课程请求参数
        if(!empty( $this->get('lesson_id'))) {
            $totalParams['lesson_id'] = $this->get('lesson_id');
            $data['lesson_id'] = $this->get('lesson_id');
        }
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(empty($classInfo)) throw new Exception("无效的班牌id");
        // 获取数据条数
        $totalParams['isDelete'] = 0;
        $totalParams['classId'] = $classInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_homework_list($totalParams);
        // 获取科目列表
        $lessonParams['schoolId'] = $classInfo['school_id'];
        $lessonParams['isDelete'] = 0;
        $lessonParams['field'] = 'id, lesson_name';
        $lessonList = $this->schoolModel->get_lesson_list($lessonParams);
        // 返回学校所有科目
        $ret['lesson'] = $lessonList;
        $lessonList = array_value_to_key($lessonList, "id");

        // 获取数据
        $data['isDelete'] = 0;
        $data['classId'] = $classInfo['id'];
        $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $data['pageSize']= ADMIN_PAGE_SIZE;
        $homeworkData = array();
        $homeworkList = $this->contentModel->get_homework_list($data);
        foreach($homeworkList as $homework) {
            if($homework['imgs']) {
                $imgArr = explode(',', $homework['imgs']);
            } else {
                $imgArr = array();
            }
            $homeworkData[] = array(
                "id" => $homework['id'],
                "title" => $homework['homework_title'],
                "content" => trim_link_tags(urlencode($homework['homework_content'])),
                "time" => $homework['createtime'],
                "updatetime" => $homework['updatetime'],
                "lesson" => $homework['lesson_id'] && isset($lessonList[$homework['lesson_id']]) ? $lessonList[$homework['lesson_id']]['lesson_name'] : '',
                'img_arr' => $imgArr,
                'file_arr' => json_decode($homework['file'])
            );
        }
        // 返回值
        $ret['total'] = $total;
        $ret['data'] = $homeworkData;

        exit(json("", true, $ret));
    }

    // 获取班级视频
    public function get_class_video_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取数据条数
        $totalParams['getRowNumber'] = true;
        $totalParams['isDelete'] = $data['isDelete'] = 0;
        $totalParams['classId'] = $data['classId'] = $classInfo['id'];
        // 过滤视频为空
        $totalParams['notEmpty'] = $data['notEmpty'] = 1;
        // $total = $this->contentModel->get_video_list($totalParams);
        // 获取数据
        // $data['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        // $data['pageSize']= ADMIN_PAGE_SIZE;
        // $data['classId'] = $classInfo['id'];
        $videoData = array();
        $videoList = $this->contentModel->get_video_list($data);

        // if($videoList) {
        //     // 判断第一条视频压缩是否完成
        //     // 加载又拍云sdk
        //     require_once('vendor/autoload.php');
        //     // 初始化又拍云接口
        //     $config = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        //     $upyun = new Upyun\Upyun($config);

        //     // 判断最新一条视频是否压缩完成
        //     $linkUpyun = str_replace(UP_URL, '', $videoList[0]['video_link']);
        //     if(!$upyun->has($linkUpyun)) {
        //         $videoList[0]['video_link'] =  isset($videoList[0]['video_old_link']) && $videoList[0]['video_old_link'] ? $videoList[0]['video_old_link'] : '';
        //     }
        // }

        foreach($videoList as $video) {
            if($video['video_link']) {
                $fileExits = check_remote_file_exists($video['video_link']);
                if(!$fileExits) $video['video_link'] = str_replace(UP_VIDEO_NEW_NAME, "", $video['video_link']);
    
                $videoData[] = array(
                    "title" => $video['video_title'],
                    "link" => $video['video_link'],
                    "poster"=> $video['video_poster'],
                    // "time" => $video['createtime'],
                    "time" => $video['updatetime'],
                    // "play_in_class_mode" => $video['play_in_class_mode'] ? true : false
                );
            }

        }
        
        // 返回值
        // $ret['total'] = $total;
        $ret['total'] = count($videoData);
        $ret['data'] = $videoData;
        exit(json("", true, $ret));
    }

    // // 获取班级相册
    // public function get_class_album_data($brandId){
    //     // 加载数据库类
    //     $this->load->model('classesModel');
    //     $this->load->model('contentModel');
    //     // 获取班牌信息
    //     $brandInfo = $this->classesModel->get_brand_info($brandId);
    //     if(!$brandInfo) exit(json("无效的班牌id", false));
    //     // 获取班级信息
    //     $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
    //     // 获取相册分类
    //     $albumData = array();
    //     $albumCategory = array();
    //     $cateByAdminParams['schoolId'] = $classInfo['school_id'];
    //     $cateByAdminParams['campusId'] = $classInfo['campus_id'];
    //     $cateByAdminParams['classId'] = $classInfo['id'];
    //     // 获取管理员发布的相册分类
    //     $cateByAdminList = $this->contentModel->get_album_category_by_admin_list($cateByAdminParams);
    //     $adminCateArr = array();
    //     foreach($cateByAdminList as $cateByAdmin) {
    //         // 获取分类
    //         $adminCateParams['categoryByAdminId'] = $cateByAdmin['id'];
    //         $adminCateList = $this->contentModel->get_album_category($adminCateParams);
    //         if(isset($adminCateList)) {
    //             $adminCateInfo = $adminCateList[0];
    //             $adminCateArr[] = $adminCateInfo;
    //         }
            
    //     }
    //     // exit(json("", true, $adminCateArr));
    //     // 获取班级相册分类
    //     $classAlbumParams['classId'] = $classInfo['id'];
    //     $classAlbumCategory = $this->contentModel->get_album_category($classAlbumParams);
    //     $albumCategory = array_merge($adminCateArr, $classAlbumCategory);
    //     // 获取相册内容
    //     foreach($albumCategory as $category) {
    //         $albumImage = array();
    //         // 获取相册内容
    //         $albumParams['categoryId'] = $category['id'];
    //         $albumParams['classId'] = $classInfo['id'];
    //         $albumImages = $this->contentModel->get_album($albumParams);
    //         if($albumImages) {
    //             foreach($albumImages as $image) {
    //                 $albumImage['category'] = $category['album_category_name'];
    //                 $albumImage['item'][] = array(
    //                     "title" => $image['image_desc'],
    //                     "link" => $image['image_link']
    //                 );
    //             }
    //             $albumData[] = $albumImage;
    //         }
    //     }
    //     // 返回值
    //     exit(json("", true, $albumData));
    // }

    // 获取班级相册
    public function get_class_album_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取相册分类
        $albumData = array();
        $albumCategory = array();
        $cateByAdminParams['schoolId'] = $classInfo['school_id'];
        $cateByAdminParams['campusId'] = $classInfo['campus_id'];
        $cateByAdminParams['classId'] = $classInfo['id'];
        // 获取管理员发布的相册分类
        $cateByAdminList = $this->contentModel->get_album_category_by_admin_list($cateByAdminParams);
        $adminCateArr = array();
        foreach($cateByAdminList as $cateByAdmin) {
            // 获取分类
            $adminCateParams['categoryByAdminId'] = $cateByAdmin['id'];
            $adminCateList = $this->contentModel->get_album_category($adminCateParams);
            if(isset($adminCateList[0])) {
                $adminCateInfo = $adminCateList[0];
                $adminCateArr[] = $adminCateInfo;
            }
            
        }
        // exit(json("", true, $cateByAdminList));
        // 获取班级相册分类
        $classAlbumParams['classId'] = $classInfo['id'];
        $classAlbumCategory = $this->contentModel->get_album_category($classAlbumParams);
        $albumCategory = array_merge($adminCateArr, $classAlbumCategory);
        // 获取相册内容
        foreach($albumCategory as $category) {
            $albumImage = array();
            // 获取相册内容
            $albumParams['categoryId'] = $category['id'];
            $albumParams['classId'] = $classInfo['id'];
            $albumImages = $this->contentModel->get_album($albumParams);
            if($albumImages) {
                foreach($albumImages as $image) {
                    $albumImage['category'] = $category['album_category_name'];
                    $albumImage['item'][] = array(
                        "title" => $image['image_desc'],
                        "link" => $image['image_link']
                    );
                }
                $albumData[] = $albumImage;
            }
        }
        // 返回值
        exit(json("", true, $albumData));
    }

    // 获取班级荣誉
    public function get_class_honor_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取相册分类
        $albumData = array();
        $params['classId'] = -1;
        $albumCategory = $this->contentModel->get_album_category($params);
        // 获取相册内容
        foreach($albumCategory as $category) {
            $albumImage = array();
            // 获取相册内容
            $albumParams['classId'] = $classInfo['id'];
            $albumParams['categoryId'] = $category['id'];
            $albumImages = $this->contentModel->get_album($albumParams);
            foreach($albumImages as $image) {
                $albumImage[] = array(
                    "title" => $image['image_desc'],
                    "link" => $image['image_link']
                );
            }
            $albumData = $albumImage;
        }
        // 返回值
        exit(json("", true, $albumData));
    }

    // 获取教师风采(教师列表)
    public function get_class_teacher_list($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        // 获取教师列表
        $teacherArray = array();
        $teacherParams['schoolId'] = $classInfo['school_id'];
        $teacherParams['isDelete'] = 0;
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');
        // 获取班级课程表
        $lessonParams['classId'] = $classInfo['id'];
        $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        foreach($lessonList as $lesson) {
            // 获取课程老师信息
            if(empty($lesson['schedule_teacher'])){
                continue;
            }
            $teacherInfo = $teacherList[$lesson['schedule_teacher']];
            $teacherArray[$teacherInfo['id']] = array(
                "id" => $teacherInfo['id'],
                "name" => $teacherInfo['realname'],
                "lesson" => $lesson['schedule_lesson'],
                "headimgurl" => $teacherInfo['headimgurl'],
                "desc" => urlencode($teacherInfo['content'])
            );
        }
        sort($teacherArray);
        exit(json("", true, $teacherArray));
    }

    // 获取学生列表
    public function get_class_student_list($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(empty($classInfo) || $classInfo['is_delete'] == 1) {
            if(!$brandInfo) exit(json("无效的班牌id", false));
        }
        // 获取班级学生人数
        $studentArray = array();
        $studentParams['classId'] = $classInfo['id'];
        $studentParams['isDelete'] = 0;
        $studentList = $this->schoolModel->get_student_list($studentParams);
        foreach($studentList as $key => $student) {
            $studentArray[] = array(
                "id" => $student['id'],
                "name" => $student['realname'],
                "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                "job" => $student['job'],
                "cardnum" => $student['realcard'],
                "faceImage" => $student['face_image']
            );
        }
        exit(json("", true, $studentArray));
    }

    // 更新学生头像
    public function update_student_face_image($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 如果是传学生ID
        if($this->post("student_id")) {
            $studentId = $this->post("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            // 获取学生信息
            $cardNum = $this->post("cardnum");
            if(!$cardNum) throw new Exception("参数错误");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($cardNum, $brandInfo['school_id']);
        }
        if(empty($studentInfo)) {
            throw new Exception('参数错误');
        }
        if($studentInfo['school_id'] != $brandInfo['school_id']) {
            throw new Exception('参数错误');
        }

        // 获取图片base64值
        $imageBase64 = $this->post("student_face_image", false);
        $imageType = get_img_type_from_base64($imageBase64);
        if(!$imageType) throw new Exception("更新失败，图片参数错误");
        // // 写入图片
        // require_once('vendor/autoload.php');
        // $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".". $imageType;
        // $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        // $client = new Upyun\Upyun($serviceConfig);
        // $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
        // if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");
        $this->load->library('localUploader');
        $webUrl = $this->localuploader->uploadBase64Image($imageBase64);
        if($webUrl == false) {
            throw new Exception('系统错误，请联系管理员');
        }
        $update['face_image'] = $webUrl;
        // 更新图片
        // $update['face_image'] = UP_URL. $fileName;
        $this->db->update(SchoolModel::$schoolStudentTable, $update, "id='{$studentInfo['id']}'");

        // 插入闸机任务
        $gateParams['schoolId'] = $brandInfo['school_id'];
        $gateParams['campusId'] = $brandInfo['campus_id'];
        // 过滤软删除
        $gateParams['isDelete'] = 0;
        $gateList = $this->schoolModel->get_gate_list($gateParams);
        if($gateList) {
            if($studentInfo['face_image']) {
                // 更新
                $taskType = GATE_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $taskType = GATE_TASK_TYPE_ADD;
            }
            $insertTaskBatch = array();
            foreach($gateList as $gate) {
                array_push($insertTaskBatch, array(
                    'school_id' => $brandInfo['school_id'],
                    'campus_id' => $brandInfo['campus_id'],
                    'gate_id' => $gate['id'],
                    'device_sn' => $gate['device_sn'],
                    'user_id' => $studentInfo['id'],
                    'user_name' => $studentInfo['realname'],
                    'user_face_image' => $update['face_image'],
                    'user_type' => GATE_USER_TYPE_STUDENT,
                    'task_type' => $taskType,
                    'task_state' => GATE_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
            }
        }

        // 插入一体机任务
        $this->load->model('aioModel');
        $aioParams['schoolId'] = $brandInfo['school_id'];
        $aioParams['campusId'] = $brandInfo['campus_id'];
        // 过滤软删除
        $aioParams['isDelete'] = 0;
        $aioList = $this->aioModel->get_aio_list($aioParams);
        if($aioList) {
            if($studentInfo['face_image']) {
                // 更新
                $taskType = AIO_TASK_TYPE_UPDATE;
            } else {
                // 新增
                $taskType = AIO_TASK_TYPE_ADD;
            }
            $insertTaskBatch = array();
            foreach($aioList as $aio) {
                array_push($insertTaskBatch, array(
                    'school_id' => $brandInfo['school_id'],
                    'campus_id' => $brandInfo['campus_id'],
                    'aio_id' => $aio['id'],
                    'facesluice_id' => $aio['facesluice_id'],
                    'user_id' => $studentInfo['id'],
                    'user_name' => $studentInfo['realname'],
                    'user_face_image' => $update['face_image'],
                    'user_type' => AIO_USER_TYPE_STUDENT,
                    'task_type' => $taskType,
                    'task_state' => AIO_TASK_STATE_NEW,
                    'createtime' => date('Y-m-d H:i:s'),
                    'updatetime' => date('Y-m-d H:i:s')
                ));
            }
            if($insertTaskBatch) {
                $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
            }
        }

        // 返回成功提示和头像地址
        exit(json("头像上传成功", true,  $update['face_image']));
    }

    // 更新学生卡号
    public function update_student_cardnum($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->post("student_id"))) {
            throw new Exception('参数错误');
        }
        if(empty(trim($this->post("cardnum")))) {
            throw new Exception('参数错误');
        }
        $studentId = $this->post("student_id");
        $studentInfo = $this->schoolModel->get_student_info($studentId);
        if(empty($studentInfo)) {
            throw new Exception('参数错误');
        }
        if($studentInfo['school_id'] != $brandInfo['school_id']) {
            throw new Exception('参数错误');
        }
        $cardNum = trim($this->post("cardnum"));
        // 学校内物理卡号唯一
        $student = $this->schoolModel->get_student_info_by_realcard($cardNum, $studentInfo['school_id'], $studentId);
        if(!empty($student)) {
            throw new Exception('物理卡号已被占用');
        }

        // 更新卡号
        $update['realcard'] = $cardNum;
        $update['updatetime'] = date('Y-m-d H:i:s');
        $this->db->update(SchoolModel::$schoolStudentTable, $update, "id='{$studentInfo['id']}'");

        // 返回成功提示和头像地址
        exit(json("卡号更新成功", true));
    }

    // 获取APP版本
    public function get_app_version($brandId){
        // 获取系统配置类
        $this->load->model('configModel');
        $this->load->model('classesModel');
        $this->load->model('schoolModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("参数错误");
        // 获取班级信息
        $schoolInfo = $this->schoolModel->get_school_info($brandInfo['school_id']);
        if(!$schoolInfo) throw new Exception("参数错误");

        // 获取版本号
        $versionName = $this->configModel->get_config_info('app_version', true);
        $versionCode = intval($this->configModel->get_config_info('app_version_code', true));
        // 如果关闭班牌更新
        if(!$schoolInfo['school_brand_update']) {
            $versionName = "0.0.0";
            $versionCode = 0;
        }

        $ret['version'] = $versionName;
        $ret['versionCode'] = $versionCode;
        $ret['app'] = $this->configModel->get_config_info('app_link', true);
        $ret['app2'] = $this->configModel->get_config_info('app_link2', true);


        exit(json("", true, $ret));
    }

    // 根据地区编码，获取下级地区列表
    public function get_area_list($areaCode){
        // 加载数据库类
        $this->load->model('schoolModel');
        $areaInfo = $this->schoolModel->get_area_info($areaCode);
        // 获取城市列表
        $areaParams['parentId'] = $areaInfo['id'];
        $areaList = $this->schoolModel->get_area_list($areaParams);
        exit(json("", true, $areaList));
    }

    // 学生课程签到接口（版本2）
    public function student_sign_v2($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('staffModel');
        $this->load->model('dataModel');
        // 签到类型
        $signType = $this->post("sign_type") ? $this->post("sign_type") : SIGN_TYPE_CARD;
        // 签到图片，base64与url二选一
        $imageBase64 = $this->post("sign_image", false);
        $imageUrl = $this->post("sign_image_url");
        if(empty($imageBase64) && empty($imageUrl)) {
            throw new Exception('图片参数不能为空');
        }
        if($imageBase64 && $imageUrl) {
            throw new Exception('图片参数错误');
        }
        if($imageBase64) {
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("签到失败，图片参数错误");
        }

        // 签到时间
        $signTime = $this->post("sign_time");
        if(!$signTime) throw new Exception("签到失败，签到时间不能为空");
        // 是否离校
        $isLeave = $this->post("is_leave") ? $this->post("is_leave") : 0;
        // 是否补签
        $isSupplement = $this->post('is_supplement') ? $this->post('is_supplement') : 0;

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        // 如果有传课程ID，则根据当前课程获取班级信息
        $isTeachingSign = false; // 是否走班
        $isElectiveSign = false;
        $courseId = $this->post("course_id") ? $this->post("course_id") : 0;
        if(!$courseId) throw new Exception("签到失败，课程id参数错误");
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
            if($courseInfo['class_id'] != $brandInfo['class_id']) {
                $isTeachingSign = true;
                // 判断是否为选修班
                if($classInfo['class_type'] == CLASSES_TYPE_ELECTIVE) {
                    $isElectiveSign = true;
                }
            }
        } else {
            // 获取班级信息
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }
        if(!$classInfo) throw new Exception("签到失败，获取不到当前课程班级信息");
        // 判断温度
        if($signType == SIGN_TYPE_TEMPERATURE || $signType == SIGN_TYPE_TEMPERATURE_HEAD || $signType == SIGN_TYPE_TEMPERATURE_WRIST) {
            if(empty($this->post('temperature'))) {
                throw new Exception("缺少温度参数");
            }
        }
        
        // 获取学生信息
        if($this->post('student_id')) {
            $studentId = $this->post('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            $realcard = $this->post("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        }
        if(!$studentInfo) throw new Exception("签到失败，找不到对应的学生");
        // 获取兴趣班id
        $teachClassArray = explode(",", $studentInfo['teaching_class_id']);
        $electiveClassArray = explode(",", $studentInfo['elective_class_id']);
        if($studentInfo['class_id'] != $classInfo['id'] && !in_array($classInfo['id'], $teachClassArray) && !in_array($classInfo['id'], $electiveClassArray)) {
            // throw new Exception("签到失败，该名学生不在本班级上课");
            exit(json('签到失败，该名学生不在本班级上课', true));
        }
 
        // 检查今天是否已签到
        // $todaySign = $this->classesModel->get_today_sign($studentInfo['id'], $classInfo['id']);
        // if($todaySign) throw new Exception("你今天已经签到，无需重复签到");
        // 判断10分钟内是否有重复提交
        $signInfo = $this->classesModel->get_sign_info_by_createtime(date("Y-m-d H:i:s", strtotime($signTime)), $studentInfo['id'], $courseId);
        if($signInfo) {
            // 测试服不限制
            if(ENV != 'test' && ENV != 'local') {
                // throw new Exception('10分钟内不需要重复签到');
                exit(json('10分钟内不需要重复签到', true));
            }
        }
        // // 判断当天是否有重复提交
        // $signInfo = $this->classesModel->get_sign_info_by_sign_date(date("Y-m-d", strtotime($signTime)), $studentInfo['id'], $courseId);
        // if($signInfo) {
        //     throw new Exception('你今天已经签到，无需重复签到');
        // }

        if($imageBase64) {
            $this->load->library('localUploader');
            $signImg = $this->localuploader->uploadBase64Image($imageBase64);
            if($signImg == false) {
                throw new Exception('系统错误，请联系管理员');
            }
        } else {
            // 图片url
            $signImg = $imageUrl;
        }
        if($this->post('temperature')) {
            $temperature = $this->post('temperature');
            if(!is_numeric($temperature)) {
                throw new Exception("温度格式错误");
            }
            // 限制为1位小数
            $temperature = sprintf("%.1f", $temperature);
        } else {
            $temperature = '';
        }
        // 处理签到状态
        if($isLeave) {
            $state = SIGN_STATE_LEAVE;
        } else {
            // 判断是否补签
            if($isTeachingSign) {
                if($isElectiveSign) {
                    // 选修班
                    if($isSupplement) {
                        $state = SIGN_STATE_ELECTIVE_SUPPLEMENT;
                    } else {
                        $state = SIGN_STATE_ELECTIVE;
                    }
                } else {
                    // 走班
                    if($isSupplement) {
                        $state = SIGN_STATE_TEACH_SUPPLEMENT;
                    } else {
                        $state = SIGN_STATE_TEACH;
                    }
                }
            } else {
                // 行政班
                if($isSupplement) {
                    $state = SIGN_STATE_NORMAL_SUPPLEMENT;
                } else {
                    $state = SIGN_STATE_NORMAL;
                }
            }
        }

        // 判断是否‘重新签到’的签到
        // 获取之前最近的重新签到课程，包含本节课
        $schduleParams['schoolId'] = $brandInfo['school_id'];
        $schduleParams['campusId'] = $brandInfo['campus_id'];
        $schduleParams['isThisWeek'] = 1;
        // 兼容不同年级作息
        $schduleParams['gradeId'] = $classInfo['grade_id'];
        $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
        $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
        $classIndex = 1;
        $time = date("H:i:s", strtotime($signTime));
        foreach($timeArr as $lessonKey => $lessonTime) {  
            // 如未设置，默认为10
            if(!isset($lessonTime['sign_interval'])) {
                $lessonTime['sign_interval'] = 10;
            }
            // 课程结束时间
            $signStartTime = date("H:i", strtotime($lessonTime['beginTime']) - ($lessonTime['sign_interval']) * 60) . ':00';
            // 小于第一节情况
            if($lessonKey == 0) {
                if($time <= $signStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
            // 大于最后一节情况
            if($lessonKey == count($timeArr) - 1) {
                if($time >= $signStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
            // 其他情况
            if($lessonKey < count($timeArr) - 1) {
                if(!isset($timeArr[$lessonKey + 1]['sign_interval'])) {
                    $timeArr[$lessonKey + 1]['sign_interval'] = 10;
                }
                // 下节课考勤开始时间
                $nextSignStartTime = date("H:i", strtotime($timeArr[$lessonKey + 1]['beginTime']) - ($timeArr[$lessonKey + 1]['sign_interval']) * 60) . ':00';
                // 大于等于当前考勤开始时间，小于下节考勤开始时间
                if($time >= $signStartTime && $time < $nextSignStartTime) {
                    $classIndex = $lessonTime['timeslotInDay'];
                    break;
                }
            }
        }
        $refreshClassIndex = 0;
        foreach($timeArr as $key => $time) {
            if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
                $refreshClassIndex = $key + 1;
            }
        }
        $date = date("Y-m-d", strtotime($signTime));
        // 获取学生当天最后一次签到
        $signData = $this->dataModel->get_student_sign_data($date, $studentInfo['id']);

        if($signData['sign_id'] && $signData['schedule_class_index'] >= $refreshClassIndex) {
            // 不是‘重新签到’
            $refreshSign = false;
        } else {
            // 是‘重新签到’
            $refreshSign = true;
        }

        // 如果是同步学校，设置sign_is_submit=1
        $schoolInfo = $this->schoolModel->get_school_info($studentInfo['school_id']);
        if($schoolInfo['school_from'] == X_DATA_HAOZHUANYE) {
            $insert['sign_is_submit'] = 1;
        } else {
            $insert['sign_is_submit'] = 0;
        }

        // 入库，做个毛线逻辑
        $insert['school_id'] = $classInfo['school_id'];
        $insert['class_id'] = $classInfo['id'];
        $insert['course_id'] = $courseId;
        $insert['student_id'] = $studentInfo['id'];
        $insert['student_card_number'] = $studentInfo['realcard'];
        $insert['brand_id'] = $brandInfo['id'];
        $insert['sign_type'] = $signType;
        $insert['state'] = $state;
        $insert['sign_img'] = $signImg;
        $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
        $insert['temperature'] = $temperature;
        $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
        $this->db->insert(ClassesModel::$signTable, $insert);

        // 返回值
        $ret['name'] = $studentInfo['realname'];
        $ret['signId'] = $this->db->insert_id();

         // 插入考勤临时表
         $this->db->insert(ClassesModel::$signTempTable, $insert);

        // 发送模板消息
        $url = wx_url('pub/student_sign_detail/' . $ret['signId']);
        $data = array(
            'first' => array(
                'value' => '家长您好，' . $studentInfo['realname'] . '同学已经成功签到'
            ),
            'keyword1' => array(
                'value' => $classInfo['class_name']
            ),
            'keyword2' => array(
                'value' => date("Y-m-d H:i:s", strtotime($signTime))
            ),
            'keyword3' => array(
                'value' => $studentInfo['realname']
            )
        );
        $this->load->library('wxtemplate');
        if($refreshSign == true) {
            // 重新签到才发送模板消息
            $this->wxtemplate->send_template_msg_for_user($studentInfo['id'], BIND_TYPE_STUDENT, WX_TEMPLATE_SCHEDULE, $data, $url);
        }

        if($temperature && $temperature > 37.2 && $temperature < TEMPERATURE_UNKNOWN) {
            // 获取该学生的班主任
            $class = $this->classesModel->get_class_info($studentInfo['class_id']);
            $masterCoach = $this->staffModel->get_master_coach_by_class($class['id']);
            if($masterCoach) {
                $masterInfo = $this->schoolModel->get_school_user_info_realname($masterCoach['teacher_id']);
            } else {
                $masterInfo = NULL;
            }
            if($masterInfo) {
                // 发送体温模板消息给班主任
                $url = wx_url('pub/student_sign_detail/' . $ret['signId']);
                $temp = handle_temperature($temperature);
                if($temp == '未知') {
                    $temperatureStr = '未知';
                } else {
                    $temperatureStr = $temp . '℃';
                }

                $data = array(
                    'first' => array(
                        'value' => '您好，收到学生测温异常通知'
                    ),
                    'keyword1' => array(
                        'value' => $studentInfo['realname']
                    ),
                    'keyword2' => array(
                        'value' => $temperatureStr
                    ),
                    'keyword3' => array(
                        'value' => date("Y-m-d H:i:s", strtotime($signTime))
                    )
                );

                $this->wxtemplate->send_template_msg_for_user($masterInfo['id'], BIND_TYPE_TEACHER, WX_TEMPLATE_TEMPEARTURE, $data, $url);
            }
        }
        exit(json("", true, $ret));
    }

    // socket通知
    public function alert_socket(){
        // $toChannel = str_replace(CHANNEL_ID_PREFIX, "", $this->post("to"));
        // 本地部署不需要去掉前缀
        $toChannel = $this->post("to");

        $contentType = $this->post("type");
        $content = $this->post("msg", false);

        // 如果是屏幕截图
        if($contentType == CONTENT_TYPE_SCREENSHOT) {
            // 获取图片base64值
            $imageType = get_img_type_from_base64($content);
            if(!$imageType) throw new Exception("更新失败，图片参数错误");

            $this->load->library('localUploader');
            $content = $this->localuploader->uploadBase64Image($content);
            if($content == false) {
                throw new Exception('系统错误，请联系管理员');
            }

            // // 写入图片
            // require_once('vendor/autoload.php');
            // $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".". $imageType;
            // $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            // $client = new Upyun\Upyun($serviceConfig);
            // $result = $client->write("/". $fileName, file_get_contents($content));   // 上传图片，自动创建目录
            // if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

            // $content = UP_URL. $fileName;
        }

        // socket值
        $socketData['type'] = $contentType;
        $socketData['content'] = $content;

        // $socketData['channel_id'] = $toChannel;

        // 推送消息到客户端
        $this->load->library('socket');
        // $this->socket->send_sae_channel_msg($toChannel, $socketData);
        $this->socket->send_channel_msg($toChannel, $socketData);
        

        exit(json("", true));
    }

     // 检查当前课程信息（已废弃）
    public function get_current_course($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        if(!$classInfo['classroom_id']) exit(json("不存在的教室ID", false));

        // 获取本周课程
        $schedule = $this->classesModel->get_campus_schedule($classInfo['campus_id']);
        $timeJson = json_decode($schedule['schedule_time_json'], true);
        // 获取当前时间
        $currentTime = $this->post('time') ? $this->post('time') : date("H:i");
        // 当前课程节数
        $courseIndex = 0;
        $courseStartTime = $courseEndTime = "";
        // 判断timejson是否为NULL
        if(null !== $timeJson){
            // 获取当前时间是第几节课
            foreach($timeJson as $timePoint) {
                $signIntervalTemp = $brandInfo['sign_interval'];
                // 安康市小学上午和下午第一节写死
                // if($classInfo['school_id'] == 27 || $classInfo['school_id'] == 30) {
                if($classInfo['school_id'] == 27) {
                    if(($currentTime >= '07:20' && $currentTime <= '08:00') || ($currentTime >= '13:20' && $currentTime <= '14:00')) {
                        $signIntervalTemp = 41;
                    }
                }
                if(ENV == 'test') {
                    if($classInfo['school_id'] == 27 || $classInfo['school_id'] == 30) {
                        if(($currentTime >= '07:20' && $currentTime <= '08:00') || ($currentTime >= '13:20' && $currentTime <= '14:00')) {
                            $signIntervalTemp = 41;
                        }
                    }  
                }
                // 下东圃写死
                if($classInfo['school_id'] == 24) {
                    if($currentTime >= '06:30' && $currentTime <= '08:00') {
                        $signIntervalTemp = 90;
                    }
                    if($currentTime >= '12:00' && $currentTime <= '13:10') {
                        $signIntervalTemp = 70;
                    }
                }
                if(ENV == 'test') {
                    if($classInfo['school_id'] == 30) {
                        if($currentTime >= '06:30' && $currentTime <= '08:00') {
                            $signIntervalTemp = 90;
                        }
                        if($currentTime >= '12:00' && $currentTime <= '13:10') {
                            $signIntervalTemp = 70;
                        }
                    } 
                }
                $signInterval = '-' . $signIntervalTemp . 'minutes';
                $classStart = date("H:i", strtotime($timePoint['beginTime'] . $signInterval));                       // 课程开始时间
                $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));   // 课程结束时间

                // if($classStart <= $currentTime && $classEnd > $currentTime) {
                if($currentTime > $classStart && $currentTime <= $classEnd) {
                    $courseIndex = $timePoint['timeslotInDay'];
                    $courseStartTime = $timePoint['beginTime'];
                    $courseEndTime = $classEnd;
                }
            }
        }
        // 获取本周指定课程信息
        $weekIndex = date("w",time());
        $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
        // 获取本次上课信息
        $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);
        if(!$courseIndex || !$scheduleLesson) exit(json("没有对应课程"));

        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info($scheduleLesson['schedule_teacher']);
        // 获取当前班级信息
        $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
        // 返回课程信息
        $ret['courseId'] = $scheduleLesson['id'];
        $ret['startTime'] = $courseStartTime;
        $ret['endTime'] = $courseEndTime;
        $ret['className'] = $courseClassInfo['class_name'] ? $courseClassInfo['class_name'] : '';
        $ret['lessonName'] = $scheduleLesson['schedule_lesson'];
        $ret['teacherName'] = $teacherInfo['realname'] ? $teacherInfo['realname'] : '';
        $ret['teacherHeadimgurl'] = $teacherInfo['headimgurl'] ? $teacherInfo['headimgurl'] : '';

        exit(json("", true, $ret));
    }

    // 备份（将来获取课程考勤sql拆成不连表查询）
    // // 检查当前课程信息（版本2）
    // public function get_current_course_v2($brandId){
    //     // 加载数据库类
    //     $this->load->model('classesModel');
    //     $this->load->model('schoolModel');
    //     $this->load->model('dataModel');
    //     // 获取班牌信息
    //     $brandInfo = $this->classesModel->get_brand_info($brandId);
    //     if(!$brandInfo) exit(json("无效的班牌id", false));
    //     // 获取班级信息
    //     $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
    //     if(!$classInfo) exit(json("不存在的班级", false));
    //     if(!$classInfo['classroom_id']) exit(json("不存在的教室ID", false));

    //     // 获取本周课程
    //     $schedule = $this->classesModel->get_campus_schedule($classInfo['campus_id']);
    //     $timeJson = json_decode($schedule['schedule_time_json'], true);
     
    //     // 获取当前时间
    //     $currentTime = $this->post('time') ? $this->post('time') : date("H:i:s");
    //     // 当前课程节数
    //     $courseIndex = 0;
    //     $courseStartTime = $courseEndTime = $signStartTimeNew = $signEndTimeNew = "";
    //     // 判断timejson是否为NULL
    //     if(null !== $timeJson){
    //         // 获取当前时间是第几节课
    //         foreach($timeJson as $timePoint) {
    //             // 如为设置，默认为10
    //             if(!isset($timePoint['sign_interval'])) {
    //                 $timePoint['sign_interval'] = 10;
    //             }
    //             // interval如为0，走班也设置为10
    //             // 新版上课时间
    //             $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
    //             $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - ($timePoint['sign_interval']) * 60) . ':00';
    //             $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
    //             if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
    //                 $courseIndex = $timePoint['timeslotInDay'];
    //                 $courseStartTime = $timePoint['beginTime'];
    //                 $courseEndTime = $classEnd;
    //                 if($timePoint['sign_interval'] == 0) {
    //                     $signStartTimeNew = '';
    //                     $signEndTimeNew = '';
    //                 } else {
    //                     $signStartTimeNew = $signStartNew;
    //                     $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
    //                 }
    //                 break;
    //             }
    //         }
    //         // 处理走班interval设置为0的情况
    //         if($courseIndex == 0) {
    //             foreach($timeJson as $timePoint) {
    //                 // 如为设置，默认为10
    //                 if(!isset($timePoint['sign_interval'])) {
    //                     $timePoint['sign_interval'] = 10;
    //                 }
    //                 if($timePoint['sign_interval'] == 0) {
    //                     // 新版上课时间
    //                     $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
    //                     $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - 10 * 60) . ':00';
    //                     $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
    //                     if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
    //                         $courseIndex = $timePoint['timeslotInDay'];
    //                         $courseStartTime = $timePoint['beginTime'];
    //                         $courseEndTime = $classEnd;
    //                         if($timePoint['sign_interval'] == 0) {
    //                             $signStartTimeNew = '';
    //                             $signEndTimeNew = '';
    //                         } else {
    //                             $signStartTimeNew = $signStartNew;
    //                             $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
    //                         }
    //                         break;
    //                     }
    //                 }
    //             }
    //         }
    //     } else {
    //         exit(json("没有对应课程"));
    //     }
        
    //     // var_export($signStartNew);exit;
    //     // 获取本周指定课程信息
    //     $weekIndex = date("w",time());
    //     $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
    //     // 获取本次上课信息
    //     $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);
    //     if($timePoint['sign_interval'] == 0 && $scheduleLesson['class_id'] != $classInfo['id']) {
    //         // interval如为0，走班也设置为10
    //         // $signStartTimeNew = $signStartNew;
    //         // $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 10 * 60) . ':59';

    //         $signStartTimeNew = date("H:i", strtotime($courseStartTime) - 10 * 60) . ':00';
    //         $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
    //     }
    //     if(!$courseIndex || !$scheduleLesson) exit(json("没有对应课程"));

    //     // 获取教师信息
    //     $teacherInfo = $this->schoolModel->get_teacher_info($scheduleLesson['schedule_teacher']);
    //     // 获取当前班级信息
    //     $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
    //     // 返回课程信息
    //     $ret['courseId'] = $scheduleLesson['id'];
    //     $ret['startTime'] = $courseStartTime;
    //     $ret['endTime'] = $courseEndTime;
    //     // 新版上课时间
    //     $ret['startTimeNew'] = $courseStartTime . ':00';
    //     $ret['endTimeNew'] = date("H:i", strtotime($courseEndTime) - 60) . ':59';
    //     $ret['signStartTimeNew'] = $signStartTimeNew;
    //     $ret['signEndTimeNew'] = $signEndTimeNew;

    //     $ret['className'] = $courseClassInfo['class_name'] ? $courseClassInfo['class_name'] : '';
    //     $ret['lessonName'] = $scheduleLesson['schedule_lesson'];
    //     $ret['teacherName'] = $teacherInfo['realname'] ? $teacherInfo['realname'] : '';
    //     $ret['teacherHeadimgurl'] = $teacherInfo['headimgurl'] ? $teacherInfo['headimgurl'] : '';

    //     // 是否返回本节课学生考勤情况，默认不返回
    //     if($this->post('sign_data')) {
    //         // 获取之前最近的重新签到课程，包含本节课
    //         $schduleParams['schoolId'] = $brandInfo['school_id'];
    //         $schduleParams['campusId'] = $brandInfo['campus_id'];
    //         $schduleParams['isThisWeek'] = 1;
    //         $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
    //         $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
    //         $classIndex = $courseIndex;
    //         $refreshClassIndex = 0;
    //         foreach($timeArr as $key => $time) {
    //             if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
    //                 $refreshClassIndex = $key + 1;
    //             }
    //         }

    //          // 学生列表
    //          $stuParams['isDelete'] = 0;
    //          $stuParams['classORteach'] = $classInfo['id'];
    //          $stuParams['schoolId'] = $brandInfo['school_id'];
    //          $studentList = $this->schoolModel->get_student_list($stuParams);

    //         // 获取学生考勤信息
    //         $today = date("Y-m-d");
    //         $isTeachingClass = $scheduleLesson['class_id'] != $brandInfo['class_id'];
    //         // 考勤列表
    //         $signList = $this->dataModel->get_sign_data_fast($courseClassInfo, $today, $isTeachingClass, $scheduleLesson['id'], '', $brandInfo['school_id']);
    //         // 以student_id作为键值
    //         $signList = array_value_to_key($signList, 'student_id');
    //         // echo '<pre>';var_export($signList);exit;
    //         // 检查用户签到情况
    //         $signArray = array(
    //             "sign" => array(
    //                 'count' => 0,
    //                 'data' => array()
    //             ),
    //             "noSign" => array(
    //                 'count' => 0,
    //                 'data' => array()
    //             ),
    //             // 还不支持请假功能
    //             // "leave" => array()
    //         );

    //         // 临时课程数据
    //         $tempCourseArr = array();
    //         foreach($studentList as $student) {
    //             $studentData = array(
    //                 "id" => '',
    //                 "studentId" => $student['id'],
    //                 "studentCard" => $student['realcard'],
    //                 "name" => $student['realname'],
    //                 "faceImage" => $student['face_image'],
    //                 "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
    //                 'course_id' => '',
    //                 "image" => '',
    //                 "signTime" => '',
    //                 "signTimeDetail" => '',
    //                 "temperature" => '',
    //                 'state' => ''
    //             );
    //             if(isset($signList[$student['id']])) {
    //                 $signTemp = $signList[$student['id']];
    //                 $studentData['id'] = $signTemp['id'];
    //                 $studentData['course_id'] = $signTemp['course_id'];
    //                 $studentData['image'] = $signTemp['sign_img'];
    //                 $studentData['signTime'] = date("H时i分", strtotime($signTemp['createtime']));
    //                 $studentData['signTimeDetail'] = $signTemp['createtime'];
    //                 $studentData['temperature'] = $signTemp['temperature'];
    //                 $studentData['state'] = $signTemp['state'];
    //             }

    //             // 判断离校
    //             if($studentData['id'] && $studentData['state'] != SIGN_STATE_LEAVE) {
    //                 // 查询临时数组是否有class_index数据
    //                 // 如果有则读取临时数组
    //                 // 如果没有，则查询数据库。将查询数据保存到临时数组
    //                 $scheduleClassIndex = 0;
    //                 if($studentData['course_id']) {
    //                     if(isset($tempCourseArr[$studentData['course_id']])) {
    //                         $scheduleClassIndex = $tempCourseArr[$studentData['course_id']];
    //                     } else {
    //                         $courseInfo = $this->dataModel->get_school_schedule_lesson($studentData['course_id']);
    //                     }
    //                     if($courseInfo) {
    //                         $scheduleClassIndex = $courseInfo['schedule_class_index'];
    //                         $tempCourseArr[$courseInfo['id']] = $scheduleClassIndex;
    //                     }
    //                 }

    //                 // 判断签到是否在‘最近重新签到’后
    //                 if($scheduleClassIndex && $scheduleClassIndex >= $refreshClassIndex) {
    //                     $signArray['sign']['data'][] = $studentData;
    //                 } else {
    //                     $studentData['id'] = '';
    //                     $studentData['image'] = '';
    //                     $signArray['noSign']['data'][] = $studentData;
    //                 }
    //             } else {
    //                 $studentData['id'] = '';
    //                 $studentData['image'] = '';
    //                 $signArray['noSign']['data'][] = $studentData;
    //             }
    //         }
    //         $signArray['sign']['count'] = count($signArray['sign']['data']);
    //         $signArray['noSign']['count'] = count($signArray['noSign']['data']);
    //         $ret['signData'] = $signArray;
    //     }

    //     exit(json("", true, $ret));
    // }

    // 备份201118
    // 检查当前课程信息（版本2）
    public function get_current_course_v2($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        if(!$classInfo['classroom_id']) exit(json("不存在的教室ID", false));

        // 获取本周课程
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if($onlyOneSchedule) {
            $schedule = $this->classesModel->get_campus_schedule($classInfo['campus_id']);
        } else {
            // 转换date('w')获取的值为作息时间的week
            $this->load->helper('schedule');
            $week = transform__to_schedule_week(date('w'));
            // 获取当天的年级作息
            $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $week);
            if($gradeSchedule) {
                $schedule = $gradeSchedule;
            }
        }
        if(empty($schedule)) {
            exit(json("没有对应作息时间"));
        }
    
        $timeJson = json_decode($schedule['schedule_time_json'], true);

        // 获取当前时间
        $currentTime = $this->post('time') ? $this->post('time') : date("H:i:s");
        // 当前课程节数
        $courseIndex = 0;
        $courseStartTime = $courseEndTime = $signStartTimeNew = $signEndTimeNew = "";
        // 判断timejson是否为NULL
        if(null !== $timeJson){
            // 获取当前时间是第几节课
            foreach($timeJson as $timePoint) {
                // 如为设置，默认为10
                if(!isset($timePoint['sign_interval'])) {
                    $timePoint['sign_interval'] = 10;
                }
                // interval如为0，走班也设置为10
                // 新版上课时间
                $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - ($timePoint['sign_interval']) * 60) . ':00';
                $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                    $courseIndex = $timePoint['timeslotInDay'];
                    $courseStartTime = $timePoint['beginTime'];
                    $courseEndTime = $classEnd;
                    if($timePoint['sign_interval'] == 0) {
                        $signStartTimeNew = '';
                        $signEndTimeNew = '';
                    } else {
                        $signStartTimeNew = $signStartNew;
                        $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                    }
                    break;
                }
            }
            // 处理走班interval设置为0的情况
            if($courseIndex == 0) {
                foreach($timeJson as $timePoint) {
                    // 如为设置，默认为10
                    if(!isset($timePoint['sign_interval'])) {
                        $timePoint['sign_interval'] = 10;
                    }
                    if($timePoint['sign_interval'] == 0) {
                        // 新版上课时间
                        $classEnd = date("H:i", strtotime($timePoint['beginTime'] . "+{$timePoint['duration']} minutes"));
                        $signStartNew = date("H:i", strtotime($timePoint['beginTime']) - 10 * 60) . ':00';
                        $classEndNew = date("H:i", strtotime($timePoint['beginTime']) + ($timePoint['duration'] - 1) * 60) . ':59';
                        if($currentTime >= $signStartNew && $currentTime <= $classEndNew) {
                            $courseIndex = $timePoint['timeslotInDay'];
                            $courseStartTime = $timePoint['beginTime'];
                            $courseEndTime = $classEnd;
                            if($timePoint['sign_interval'] == 0) {
                                $signStartTimeNew = '';
                                $signEndTimeNew = '';
                            } else {
                                $signStartTimeNew = $signStartNew;
                                $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
                            }
                            break;
                        }
                    }
                }
            }
        } else {
            exit(json("没有对应课程"));
        }
        
        // var_export($signStartNew);exit;
        // 获取本周指定课程信息
        $weekIndex = date("w",time());
        $weekIndex = $weekIndex ? $weekIndex : 7;       // 如果是0的话，就是周日，需要替换成7
        // 获取本次上课信息
        $scheduleLesson = $this->classesModel->get_schedule_lesson_info($schedule['id'], $weekIndex, $courseIndex, $classInfo['classroom_id']);
        if($timePoint['sign_interval'] == 0 && $scheduleLesson['class_id'] != $classInfo['id']) {
            // interval如为0，走班也设置为10
            // $signStartTimeNew = $signStartNew;
            // $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 10 * 60) . ':59';

            $signStartTimeNew = date("H:i", strtotime($courseStartTime) - 10 * 60) . ':00';
            $signEndTimeNew = date("H:i", strtotime($courseStartTime) - 60) . ':59';
        }
        if(!$courseIndex || !$scheduleLesson) exit(json("没有对应课程"));

        // 是否走班课
        if($scheduleLesson['class_id'] != $classInfo['id']) {
            // 走班课
            $isTeachingLesson = true;
        } else {
            // 不是走班课
            $isTeachingLesson = false;
        }

        // 获取教师信息
        $teacherInfo = $this->schoolModel->get_teacher_info($scheduleLesson['schedule_teacher']);
        // 获取当前班级信息
        $courseClassInfo = $this->classesModel->get_class_info($scheduleLesson['class_id']);
        // 返回课程信息
        $ret['courseId'] = $scheduleLesson['id'];
        $ret['startTime'] = $courseStartTime;
        $ret['endTime'] = $courseEndTime;
        // 新版上课时间
        $ret['startTimeNew'] = $courseStartTime . ':00';
        $ret['endTimeNew'] = date("H:i", strtotime($courseEndTime) - 60) . ':59';
        $ret['signStartTimeNew'] = $signStartTimeNew;
        $ret['signEndTimeNew'] = $signEndTimeNew;

        $ret['className'] = $courseClassInfo['class_name'] ? $courseClassInfo['class_name'] : '';
        $ret['lessonName'] = $scheduleLesson['schedule_lesson'];
        $ret['teacherName'] = $teacherInfo['realname'] ? $teacherInfo['realname'] : '';
        $ret['teacherHeadimgurl'] = $teacherInfo['headimgurl'] ? $teacherInfo['headimgurl'] : '';

        // 获取科目
        $lessonInfo = $this->schoolModel->get_lesson_info_by_name($scheduleLesson['schedule_lesson'], $brandInfo['school_id']);
        // 课程模式和课程图片
        $lessonMode = '上课模式';
        $lessonImg = 'https://resource.rongmixiao.com/default/classTime.png';
        if($lessonInfo) {
            if(trim($lessonInfo['lesson_mode'])) {
                $lessonMode = trim($lessonInfo['lesson_mode']);
            }
            if(trim($lessonInfo['lesson_img'])) {
                $lessonImg = trim($lessonInfo['lesson_img']);
            }
        }
        $ret['lessonMode'] = $lessonMode;
        $ret['lessonImg'] = $lessonImg;

        // 是否返回本节课学生考勤情况，默认不返回
        if($this->post('sign_data')) {
            // 获取之前最近的重新签到课程，包含本节课
            $schduleParams['schoolId'] = $brandInfo['school_id'];
            $schduleParams['campusId'] = $brandInfo['campus_id'];
            $schduleParams['isThisWeek'] = 1;
            // 兼容不同年级作息
            $schduleParams['gradeId'] = $classInfo['grade_id'];
            $scheduleInfo = $this->classesModel->get_school_schedule_row($schduleParams);
            $timeArr = json_decode($scheduleInfo['schedule_time_json'], true);
            $classIndex = $courseIndex;
            $refreshClassIndex = 0;
            foreach($timeArr as $key => $time) {
                if(isset($time['refresh']) && $time['refresh'] == '是' && $key <= $classIndex - 1) {
                    $refreshClassIndex = $key + 1;
                }
            }
            // 获取学生考勤信息
            $today = date("Y-m-d");
            $isTeachingClass = $scheduleLesson['class_id'] != $brandInfo['class_id'];
            $studentList = $this->dataModel->get_sign_data_fast($courseClassInfo, $today, $isTeachingClass, $scheduleLesson['id'], '', $brandInfo['school_id']);
            // echo '<pre>';var_export($studentList);exit;
            // 检查用户签到情况
            $signArray = array(
                "sign" => array(
                    'count' => 0,
                    'data' => array()
                ),
                "noSign" => array(
                    'count' => 0,
                    'data' => array()
                ),
                // 还不支持请假功能
                // "leave" => array()
            );

            // echo '<pre>';var_export($studentList);exit;
            // 临时课程数据
            $tempCourseArr = array();
            foreach($studentList as $student) {
                $studentData = array(
                    "id" => $student['sign_id'],
                    "studentId" => $student['id'],
                    "studentCard" => $student['realcard'],
                    "name" => $student['realname'],
                    "image" => $student['sign_img']. "!small",
                    "signTime" => $student['signTime'] ? date("H时i分", strtotime($student['signTime'])) : '',
                    "signTimeDetail" => $student['signTime'] ? $student['signTime'] : '',
                    "faceImage" => $student['face_image'],
                    "headimgurl" => $student['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg'),
                    "temperature" => $student['temperature'] ? $student['temperature'] : ''
                );

                // 判断离校
                if($student['sign_id'] && $student['state'] != SIGN_STATE_LEAVE) {
                    // 查询临时数组是否有class_index数据
                    // 如果有则读取临时数组
                    // 如果没有，则查询数据库。将查询数据保存到临时数组
                    $scheduleClassIndex = 0;
                    if($student['course_id']) {
                        if(isset($tempCourseArr[$student['course_id']])) {
                            $scheduleClassIndex = $tempCourseArr[$student['course_id']];
                        } else {
                            $courseInfo = $this->dataModel->get_school_schedule_lesson($student['course_id']);
                        }
                        if($courseInfo) {
                            $scheduleClassIndex = $courseInfo['schedule_class_index'];
                            $tempCourseArr[$courseInfo['id']] = $scheduleClassIndex;
                        }
                    }

                    // 判断签到是否在‘最近重新签到’后
                    if($scheduleClassIndex && $scheduleClassIndex >= $refreshClassIndex) {
                        $signArray['sign']['data'][] = $studentData;
                    } else {
                        $studentData['id'] = '';
                        $studentData['image'] = '';
                        $signArray['noSign']['data'][] = $studentData;
                    }
                } else {
                    $studentData['id'] = '';
                    $studentData['image'] = '';
                    $signArray['noSign']['data'][] = $studentData;
                }
            }
            // echo '<pre>';var_export($tempCourseArr);exit;
            $signArray['sign']['count'] = count($signArray['sign']['data']);
            $signArray['noSign']['count'] = count($signArray['noSign']['data']);
            $ret['signData'] = $signArray;
        }

        // 返回‘上午考勤’
        $singTitle = '';
        if($isTeachingLesson) {
            $singTitle = '走班考勤';
        } else {
            $h = explode(':', $currentTime)[0];
            if($h >= 18) {
                $singTitle = '晚上考勤';
            } else if($h >= 12) {
                $singTitle = '下午考勤';
            } else {
                $singTitle = '上午考勤';
            }
        }
        $ret['signTitle'] = $singTitle;

        exit(json("", true, $ret));
    }

    // 获取班牌今天所有的人脸数据
    public function get_brand_face_data($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 如果有传课程ID，则根据当前课程获取班级信息
        $courseId = $this->get("course_id") ? $this->get("course_id") : 0;
        if($courseId) {
            $courseInfo = $this->classesModel->get_sch_lesson($courseId);
            $classInfo = $this->classesModel->get_class_info($courseInfo['class_id']);
            $stuParams['classORteach'] = $classInfo['id'];
            $stuParams['schoolId'] = $brandInfo['school_id'];
            $stuParams['isDelete'] = 0;
        } else {
            // 获取校区ID
            $campusId = $classInfo['campus_id'];
            // 获取课室id
            $classroomId = $classInfo['classroom_id'];

            // 获取本周课程作息
            // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
            $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
            if($onlyOneSchedule) {
                $scheduleInfo = $this->classesModel->get_campus_schedule($campusId);
            } else {
                // 转换date('w')获取的值为作息时间的week
                $this->load->helper('schedule');
                $week = transform__to_schedule_week(date('w'));
                // 获取当天的年级作息
                $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $week);
                if($gradeSchedule) {
                    $scheduleInfo = $gradeSchedule;
                }
            }

            // 获取本周所有课程
            $weekIndex = date("w",time());
            $params['weekIndex'] = $weekIndex ? $weekIndex : 7;
            if($scheduleInfo) {
                $params['scheduleId'] = $scheduleInfo['id'];
            }
            $params['classroom'] = $classroomId;
            $lessonList = $this->classesModel->get_school_schedule_lesson($params);
            // 获取所有班级，包含本班，避免无课表的情况
            $classArray = array(
                $classInfo['id']
            );
            foreach ($lessonList as $lesson) {
                if(!in_array($lesson['class_id'], $classArray)) {
                    $classArray[] = $lesson['class_id'];
                }
            }
            //  获取班级所有学生
            $stuParams['classORteach'] = implode(",", $classArray);
            $stuParams['schoolId'] = $brandInfo['school_id'];
            $stuParams['isDelete'] = 0;
        }

        $studentList = $this->schoolModel->get_student_list($stuParams);
        // 返回值
        $ret = array();
        foreach($studentList as $student) {
            $data['studentId'] = $student['id'];
            $data['studentName'] = $student['realname'];
            $data['faceImage'] = $student['face_image'];
            $data['cardNum'] = $student['realcard'];
            $ret[] = $data;
        }

        exit(json("", true, $ret));
    }

    // 获取学生课表
    public function get_student_schedule_lesson($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }
        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }

        if(!$studentInfo) throw new Exception("卡号不存在");
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);

        // 获取教师列表
        $teacherArray = array();
        $teacherParams['isDelete'] = 0;
        $teacherParams['schoolId'] = $studentInfo['school_id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        $teacherList = array_value_to_key($teacherList, 'id');

        // 获取本周课表作息
        $scheduleInfo = $this->classesModel->get_campus_schedule($studentInfo['campus_id']);
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        $onlyOneSchedule = $this->classesModel->check_is_only_one_schedule($brandInfo['school_id'], $brandInfo['campus_id']);
        if(!$onlyOneSchedule) {
            // 年级作息的天数和节数相同，取本年级的星期一作息即可
            $mondayGradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], 1);
            if($mondayGradeSchedule) {
                $scheduleInfo = $mondayGradeSchedule;
            }
        }
        
        // 解析json字符串
        $weekLesson = array();
        $scheduleSetting = json_decode($scheduleInfo['schedule_time_json'], true);
        if(!empty($scheduleSetting)){
            $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
            // 生成全部课程时间点
            for($i = 1; $i <= $scheduleInfo['schedule_week_days']; $i ++) {

                // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
                if(!$onlyOneSchedule) {
                    // 获取当天的年级作息
                    $gradeSchedule = $this->classesModel->get_one_daily_grade_schdedule_by_week($brandInfo['school_id'], $brandInfo['campus_id'], $classInfo['grade_id'], $i);
                    if($gradeSchedule) {
                        $scheduleSetting = json_decode($gradeSchedule['schedule_time_json'], true);
                        $scheduleSetting = array_value_to_key($scheduleSetting, 'timeslotInDay');
                    }
                }

                foreach($scheduleSetting as $lessonTime) {
                    $lsData['weekIndex'] = $i;
                    $lsData['classIndex'] = $lessonTime['timeslotInDay'];
                    $lsData['startTime'] = $lessonTime['beginTime'];
                    $lsData['endTime'] = date("H:i", strtotime($lessonTime['beginTime']) + $lessonTime['duration'] * 60);
                    $lsData['lessonName'] = $lsData['teacherName'] = $lsData['teacherId'] = '';
    
                    $lessonKey = $i. $lsData['classIndex'];
                    $weekLesson[$lessonKey] = $lsData;
                }
            }
        }
        
        // 判断是否年级不同作息（存在一个grade_id不等于0的即是）
        // 年级不同作息，不需要传schedule_id
        if($onlyOneSchedule) {
            $lessonParams['scheduleId'] = $scheduleInfo['id'];
        }

        // 获取班级集合
        $classArray = array_merge(explode(",", $studentInfo['class_id']), explode(",", $studentInfo['teaching_class_id']));
        // 选修班
        $classArray = array_merge($classArray, explode(",", $studentInfo['elective_class_id']));
        $lessonParams['classSet'] = trim(implode(",", $classArray), ",");
        $lessonList = $this->classesModel->get_school_schedule_lesson($lessonParams);
        // 获取班级列表
        $classParams['schoolId'] = $studentInfo['school_id'];
        $classParams['campusId'] = $studentInfo['campus_id'];
        $classParams['isDelete'] = 0;
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取课室列表
        $classroomParams['schoolId'] = $studentInfo['school_id'];
        $classroomParams['campusId'] = $studentInfo['campus_id'];
        $classroomParams['isDelete'] = 0;
        $classroomList = $this->classesModel->get_classroom_list($classroomParams);
        $classroomList = array_value_to_key($classroomList, 'id');      
        foreach($lessonList as $key => $item) {
            if(isset($classList[$item['class_id']])) {
                $lessonList[$key]['type'] = get_class_type_name($classList[$item['class_id']]['class_type']);
                if($classList[$item['class_id']]['class_type'] != CLASSES_TYPE_NORMAL && isset($classroomList[$item['schedule_room_id']])) {
                    // 教学班和选修班课程返回上课课室
                    $lessonList[$key]['location'] = $classroomList[$item['schedule_room_id']]['classroom_name'];
                } else {
                    $lessonList[$key]['location'] = '';
                }
            } else {
                $lessonList[$key]['type'] = '行政班';
                $lessonList[$key]['location'] = '';
            }

        }
        foreach($lessonList as $lesson) {
            $classLesson = $lesson['schedule_lesson'];
            // 写入课程名称
            $lessonKey = $lesson['schedule_week_index']. $lesson['schedule_class_index'];
            $weekLesson[$lessonKey]['lessonName'] = $classLesson;
            // 判断$teacherList是否存在
            $weekLesson[$lessonKey]['teacherId'] = '';
            $weekLesson[$lessonKey]['teacherName'] = '';
            if (isset($teacherList[$lesson['schedule_teacher']])) {
                $weekLesson[$lessonKey]['teacherId'] = $teacherList[$lesson['schedule_teacher']]['id'];
                $weekLesson[$lessonKey]['teacherName'] = $teacherList[$lesson['schedule_teacher']]['realname'];
            }
            $weekLesson[$lessonKey]['lessonType'] = $lesson['type'];
            $weekLesson[$lessonKey]['location'] = $lesson['location'];
        }
        // echo'<pre>';var_export($weekLesson);exit;
        foreach($weekLesson as $key => &$value) {
            // 过滤已删除
            if(!isset($value['weekIndex']) || !isset($value['classIndex'])) {
                unset($weekLesson[$key]);
                continue;
            }
            // if(empty($value['lessonName'])) {
            //     // 判断是否走班
            //     $scheduleLesson = $this->classesModel->get_schedule_lesson_info($scheduleInfo['id'], $value['weekIndex'], $value['classIndex'], $classInfo['classroom_id']);
            //     if($scheduleLesson) {
            //         $value['lessonName'] = '走班';
            //         $value['teacherName'] = isset($teacherList[$scheduleLesson['schedule_teacher']]) ? $teacherList[$scheduleLesson['schedule_teacher']]['realname'] : '';
            //     }
            // }
        }
        $ret['id'] = $studentInfo['id'];
        $ret['cardnum'] = $studentInfo['realcard'];
        $ret['name'] = $studentInfo['realname'];
        $ret['headimgurl'] = $studentInfo['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');
        $ret['className'] = $classInfo['class_name'] ? $classInfo['class_name'] : '';
        // sort($weekLesson);
        $weekLesson = array_values($weekLesson);
        $ret['lesson'] = $weekLesson;

        // 计算未读数
        $noteList = $this->wxUserModel->get_user_wx_note_list($studentInfo['id'], BIND_TYPE_STUDENT, 1);
        $filterdNoteList = array();
        $unreadArr = array();
        foreach($noteList as $note) {
            if($note['send_user_id'] === $note['receive_user_id']) {
                // 家长留言
                $otherUserId = $studentInfo['id'];
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['is_parent'] == 1) {
                    if(isset($unreadArr[$otherUserId])) {
                        $unreadArr[$otherUserId] ++;
                    } else {
                        $unreadArr[$otherUserId] = 1;
                    }
                }
            } else {
                // 教师留言
                if($note['send_user_type'] == BIND_TYPE_TEACHER) {
                    $otherUserId = $note['send_user_id'];
                } else {
                    $otherUserId = $note['receive_user_id'];
                }
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['send_user_type'] == BIND_TYPE_TEACHER) {
                    if(isset($unreadArr[$otherUserId])) {
                        $unreadArr[$otherUserId] ++;
                    } else {
                        $unreadArr[$otherUserId] = 1;
                    }
                }
            }
            if(!isset($filterdNoteList[$otherUserId])) {
                $filterdNoteList[$otherUserId] = $note; 
            }
        }
        $unreadCount = 0;
        if($filterdNoteList) {
            foreach($filterdNoteList as $key => $value) {
                $unread = isset($unreadArr[$key]) ? $unreadArr[$key] : 0;
                $unreadCount += $unread;
            }
        }
        // 计算未读总数
        $ret['unreadCount'] = $unreadCount;

        exit(json("", true, $ret));
    }

    // 获取考试列表
    public function get_class_exam_list($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取学校ID
        $schoolId = $classInfo['school_id'];
        $params['schoolId'] = $schoolId;
        // 只获取班牌对应的课室
        $classroomId = $classInfo['classroom_id'];
        $params['locationId'] = $classroomId;
        // 获取校区ID
        $campusId = $classInfo['campus_id'];
        $params['campusId'] = $campusId;
        // 根据日期排序
        $orderBy = 'day ASC, begin ASC';
        $params['orderBy'] = $orderBy;
        // 获取哪些属性
        $params['field'] = DataModel::$examRoomTable . '.id, day, begin, end, timeslot, part_of_day, lesson_id, type, exam_id';
        $list = $this->dataModel->get_exam_room_list($params);
        foreach ($list as $key => $val) {
            // 添加星期几属性
            $list[$key]['week'] = date_to_week($val['day']);
            // 添加科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
            // 计算考试时长
            $duration = get_duration($val['begin'], $val['end']);
            $list[$key]['duration'] = $duration;
             // 转换考试类型为中文
            // 判断是否同时存在等级考和合格考
            $bothHave = false;
            if('chosenExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'studyExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            if('studyExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'chosenExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);

            // timeslot都加1
            $list[$key]['timeslot'] += 1;
        }
        exit(json('', true, $list));
    }

    // 获取考场列表
    public function get_class_exam_room_list($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取学校ID
        $schoolId = $classInfo['school_id'];
        $params['schoolId'] = $schoolId;
        // 获取校区ID
        $campusId = $classInfo['campus_id'];
        $params['campusId'] = $campusId;
        // 只获取班牌对应的课室
        $classroomId = $classInfo['classroom_id'];
        $params['locationId'] = $classroomId;
        // 根据日期排序
        $params['orderBy'] = 'day ASC, begin ASC, x_detail_id ASC, id ASC';
        // 获取哪些属性
        // $params['field'] = 'ed.id, ed.x_room_id, ed.x_detail_id, ed.x_location_id, ed.room_no, ed.room_name, ed.students, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.x_lesson_id';
        // 暂时暴露id就行，方便客户端缓存
        $params['field'] = 'ed.id';
        $list = $this->dataModel->get_exam_room_detail_list($params); 
        exit(json('', true, $list));
    }

    // 获取考试的第一场考场
    public function get_first_exam_room_info($brandId, $roomId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));
        // 获取哪些属性
        $roomParams['field'] = 'ed.id, ed.location_id, ed.room_no, ed.room_name, ed.students, ed.inside_teachers, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.type, er.exam_id';
        $roomParams['roomId'] = $roomId;
        // 获取学校ID
        $schoolId = $classInfo['school_id'];
        $roomParams['schoolId'] = $schoolId;
        // 获取校区ID
        $campusId = $classInfo['campus_id'];
        $roomParams['campusId'] = $campusId;
        // 只获取班牌对应的课室
        $classroomId = $classInfo['classroom_id'];
        $roomParams['locationId'] = $classroomId;
        $roomParams['orderBy'] = 'day ASC, begin ASC, x_detail_id ASC, id ASC';
        $list = $this->dataModel->get_exam_room_detail_list($roomParams);
        if(empty($list)){
            exit(json('', true, NULL));
        }
        // 获取第一场
        $room = $list[0];
        // 添加星期几属性
        $room['week'] = date_to_week($room['day']);
        // 添加科目名
        $lessonInfo = $this->schoolModel->get_lesson_info($room['lesson_id']);
        $room['lesson_name'] = $lessonInfo['lesson_name'];
        // 获取考试位置
        $classroom = $this->classesModel->get_classroom_info($room['location_id'], 1);
        $room['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
        // 移除考试位置id
        unset($room['x_location_id']);
        // 计算考试时长
        $duration = get_duration($room['begin'], $room['end']);
        $room['duration'] = $duration;
        $students = json_decode($room['students'], true);
        if (null !== $students) {
            foreach($students as $stuKey => $student){
                $studentInfo = $this->schoolModel->get_student_info($student['userID']);
                // 设置默认值
                $students[$stuKey]['name'] = '';
                $students[$stuKey]['class_name'] = '';
                if(empty($studentInfo)){
                    $students[$stuKey]['userID'] = '';
                    continue;
                }
                // 获取学生姓名
                $students[$stuKey]['name'] = $studentInfo['realname'];
                // 获取学生班级名称
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $students[$stuKey]['class_name'] = $class['class_name'];
                // 获取学生账号xid
                $students[$stuKey]['userID'] = $studentInfo['x_student_id'];
            }
        }
        $room['students'] = $students;
        // 设置监考老师
        $teacherIdArr = explode(',', $room['inside_teachers']);
        $teacherArr = array();
        foreach($teacherIdArr as $id){
            $teacher = $this->schoolModel->get_teacher_info($id);
            if(!empty($teacher)){
                $teacherArr[] = $teacher['realname'];
            }
        }
        $room['inside_teachers'] = $teacherArr;

        // 转换考试类型为中文
        // 判断是否同时存在等级考和合格考
        $bothHave = false;
        if('chosenExam' === $room['type']){
            $queryParams['examId'] = $room['exam_id'];
            $queryParams['lessonId'] = $room['lesson_id'];
            $queryParams['day'] = $room['day'];
            $queryParams['timeslot'] = $room['timeslot'];
            $queryParams['type'] = 'studyExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        if('studyExam' === $room['type']){
            $queryParams['examId'] = $room['exam_id'];
            $queryParams['lessonId'] = $room['lesson_id'];
            $queryParams['day'] = $room['day'];
            $queryParams['timeslot'] = $room['timeslot'];
            $queryParams['type'] = 'chosenExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        $room['type'] = transform_type($room['type'], $room['lesson_name'], $bothHave);

        exit(json('', true, $room));
    }

    // 通过考场id获取考场详情
    public function get_exam_room_info($id){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取哪些属性
        $roomParams['field'] = 'ed.id, ed.x_detail_id, ed.location_id, ed.room_no, ed.room_name, ed.students, ed.inside_teachers, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.type, er.x_exam_id, er.exam_id';
        $room = $this->dataModel->get_exam_room_detail_info($id, $roomParams);
        if(empty($room)){
            throw new Exception('该考场id不存在');
        }
        // 添加星期几属性
        $room['week'] = date_to_week($room['day']);
        // 添加科目名
        $lessonInfo = $this->schoolModel->get_lesson_info($room['lesson_id']);
        $room['lesson_name'] = $lessonInfo['lesson_name'];
        // 获取考试位置
        $classroom = $this->classesModel->get_classroom_info($room['location_id'], 1);
        $room['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
        // 移除考试位置id
        unset($room['location_id']);
        // 计算考试时长
        $duration = get_duration($room['begin'], $room['end']);
        $room['duration'] = $duration;
        $students = json_decode($room['students'], true);
        if (null !== $students) {
            foreach($students as $stuKey => $student){
                $studentInfo = $this->schoolModel->get_student_info($student['userID']);
                // 设置默认值
                $students[$stuKey]['name'] = '';
                $students[$stuKey]['class_name'] = '';
                if(empty($studentInfo) || $studentInfo['is_delete'] == 1){
                    $students[$stuKey]['userID'] = '';
                    continue;
                }
                // 获取学生姓名
                $students[$stuKey]['name'] = $studentInfo['realname'];
                // 获取学生班级名称
                $class = $this->classesModel->get_class_info($studentInfo['class_id']);
                $students[$stuKey]['class_name'] = $class['class_name'];
                // 获取学生账号xid
                $students[$stuKey]['userID'] = $studentInfo['x_student_id'];
            }
        }
        $room['students'] = $students;
        // 设置监考老师
        $teacherIdArr = explode(',', $room['inside_teachers']);
        $teacherArr = array();
        foreach($teacherIdArr as $id){
            $teacher = $this->schoolModel->get_teacher_info($id);
            if(!empty($teacher)){
                $teacherArr[] = $teacher['realname'];
            }
        }
        $room['inside_teachers'] = $teacherArr;
       
        // 转换考试类型为中文
        // 判断是否同时存在等级考和合格考
        $bothHave = false;
        if('chosenExam' === $room['type']){
            $queryParams['examId'] = $room['exam_id'];
            $queryParams['lessonId'] = $room['lesson_id'];
            $queryParams['day'] = $room['day'];
            $queryParams['timeslot'] = $room['timeslot'];
            $queryParams['type'] = 'studyExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        if('studyExam' === $room['type']){
            $queryParams['examId'] = $room['exam_id'];
            $queryParams['lessonId'] = $room['lesson_id'];
            $queryParams['day'] = $room['day'];
            $queryParams['timeslot'] = $room['timeslot'];
            $queryParams['type'] = 'chosenExam';
            $queryRes = $this->dataModel->get_exam_room_list($queryParams);
            if(!empty($queryRes)){
                $bothHave = true;
            }
        }
        $room['type'] = transform_type($room['type'], $room['lesson_name'], $bothHave);

        exit(json('', true, $room));
    }

    // 获取学生个人考试安排列表
    public function get_student_exam_list($brandId){
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 获取班牌绑定的班级
        $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        if(!$classInfo) exit(json("不存在的班级", false));

        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("接口错误，不存在的学生ID");
        $studentId = $studentInfo['id'];
        $params['studentId'] = $studentId;
        // 获取学校ID
        $schoolId = $classInfo['school_id'];
        $params['schoolId'] = $schoolId;
        // // 只获取班牌对应的课室
        // $classroomId = $classInfo['classroom_id'];
        // $params['locationId'] = $classroomId;
        $params['field'] = 'ed.id, ed.location_id, ed.room_no, ed.room_name, ed.students, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.type, er.exam_id';
        $params['orderBy'] = 'day ASC, begin ASC';
        $list = $this->dataModel->get_exam_room_detail_list($params);

        foreach ($list as $key => $val) {
            $students = json_decode($val['students'], true);
            // 设置默认值
            $list[$key]['student_id'] = '';
            $list[$key]['seatNO'] = '';
            $list[$key]['studentTicket'] = '';
            foreach($students as $student){
                // 设置学生账号
                if ($student['userID'] == $studentId){
                    $list[$key]['student_id'] = $student['userID'];
                }  
                // 获取座位号
                if ($student['userID'] == $studentId){
                    $list[$key]['seatNO'] = $student['seatNO'];
                }
                // 获取准考证号
                if ($student['userID'] == $studentId){
                    $list[$key]['studentTicket'] = $student['studentTicket'] ? $student['studentTicket'] : '';
                }
            }
            // 移除students属性
            unset($list[$key]['students']);
            // 添加星期几属性
            $list[$key]['week'] = date_to_week($val['day']);
            // 添加科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
            // 获取考试位置
            $classroom = $this->classesModel->get_classroom_info($val['location_id'], 1);
            $list[$key]['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
            // 移除考试位置id
            unset($list[$key]['location_id']);
            // 计算考试时长
            $duration = get_duration($val['begin'], $val['end']);
            $list[$key]['duration'] = $duration;

            // 转换考试类型为中文
            // 判断是否同时存在等级考和合格考
            $bothHave = false;
            if('chosenExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'studyExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            if('studyExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'chosenExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);

            // timeslot都加1
            $list[$key]['timeslot'] += 1;
        }  

        exit(json('', true, $list));
    }

    // 获取当天考试安排表
    public function get_day_exam_list($brandId, $day){
        if(0 === preg_match("/^\d{4}-\d{2}-\d{2}$/", $day)) {
            throw new Exception('日期格式不正确');
        }
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        $this->load->model('schoolModel');
        // 获取班牌对应的课室
        // 先获取班牌对应的班级
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(empty($brandInfo)){
            throw new Exception('该班牌不存在');
        }
        $classId = $brandInfo['class_id'];
        $classInfo = $this->classesModel->get_class_info($classId);
        if(empty($classInfo)){
            throw new Exception('该班牌没有对应的班级');
        }
        $classroomId = $classInfo['classroom_id'];
        // 获取对应的课室
        if(empty($classroomId)){
            // throw new Exception('该班牌没有对应的课室');
            exit(json('该班牌没有对应的课室', true));

        }
        // 获取学校ID
        $schoolId = $classInfo['school_id'];
        $params['schoolId'] = $schoolId;
        // 获取学校ID
        $campusId = $classInfo['campus_id'];
        $params['campusId'] = $campusId;
        // 过滤课室
        $params['locationId'] = $classroomId;
        // 获取哪些属性
        $params['field'] = 'ed.id, ed.location_id, ed.room_no, ed.room_name, ed.inside_teachers, er.day, er.begin, er.end, er.timeslot, er.part_of_day, er.lesson_id, er.grade_id, er.exam_entry_time_before, er.exam_entry_time_after, er.type, er.exam_id';
        // 根据日期排序
        $params['orderBy'] = 'day ASC, begin ASC';
        // 日期参数
        $params['day'] = $day;
        $list = $this->dataModel->get_exam_room_detail_list($params);
        foreach ($list as $key => $val) {
            // 添加星期几属性
            $list[$key]['week'] = date_to_week($val['day']);
            // 添加科目名
            $lessonInfo = $this->schoolModel->get_lesson_info($val['lesson_id']);
            $list[$key]['lesson_name'] = $lessonInfo['lesson_name'];
            // 获取考试位置
            $classroom = $this->classesModel->get_classroom_info($val['location_id'], 1);
            $list[$key]['location'] = isset($classroom['classroom_name']) ? $classroom['classroom_name'] : '';        
            // 移除考试位置id
            unset($list[$key]['location_id']);
            // 计算考试时长
            $duration = get_duration($val['begin'], $val['end']);
            $list[$key]['duration'] = $duration;
            // 获取考试年级
            $list[$key]['grade'] = '';
            if(!empty($val['grade_id'])){
                $grade = $this->classesModel->get_grade_info($val['grade_id']);
                $list[$key]['grade'] = $grade['grade_name'];
                unset($list[$key]['grade_id']);
            }
            // 获取场内监考老师
            $list[$key]['inside_teachers'] = [];
            if(isset($val['inside_teachers'])){
                $idArr = explode(',', $val['inside_teachers']);
                $nameArr = array();
                foreach($idArr as $id) {
                    $teacher = $this->schoolModel->get_teacher_info($id);
                    $name = '';
                    if(null !== $teacher){
                        $name = $teacher['realname'];
                    }
                    $nameArr[] = $name;
                }
                $list[$key]['inside_teachers'] = $nameArr;
            }
            
            // 转换考试类型为中文
            // 判断是否同时存在等级考和合格考
            $bothHave = false;
            if('chosenExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'studyExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            if('studyExam' === $list[$key]['type']){
                $queryParams['examId'] = $list[$key]['exam_id'];
                $queryParams['lessonId'] = $list[$key]['lesson_id'];
                $queryParams['day'] = $list[$key]['day'];
                $queryParams['timeslot'] = $list[$key]['timeslot'];
                $queryParams['type'] = 'chosenExam';
                $queryRes = $this->dataModel->get_exam_room_list($queryParams);
                if(!empty($queryRes)){
                    $bothHave = true;
                }
            }
            $list[$key]['type'] = transform_type($list[$key]['type'], $list[$key]['lesson_name'], $bothHave);
            unset($list[$key]['timeslot']);

            // 计算考勤时间
            $list[$key]['sign_begin_time'] = date('H:i:s', strtotime($val['begin']) - $val['exam_entry_time_before'] * 60);
            $list[$key]['sign_end_time'] = date('H:i:s', strtotime($val['begin']) + $val['exam_entry_time_after'] * 60);
        }
        
        exit(json('', true, $list));
    }

    // 学生考试签到接口
    public function student_exam_sign($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 判断班牌是否存在
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("无效的班牌id");
        // 判断考场id是否存在
        $examRoomId = $this->post('exam_room_id');
        if(null === $examRoomId){
            throw new Exception('考试id不能为空');
        }
        // 判断考场id是否有效
        $roomParams['field'] = 'students';
        $info = $this->dataModel->get_exam_room_detail_info($examRoomId, $roomParams);
        if(null === $info){
            throw new Exception('考试id无效');
        }
        $students = json_decode($info['students'], true);
        // 签到类型
        if($this->post("sign_type")) {
            $signType = $this->post("sign_type");
        } else {
            $signType = SIGN_TYPE_FACE;
        }

        // 签到状态
        if($this->post("is_supplement")) {
            if($this->post("is_supplement") == 1) {
                $state = SIGN_STATE_EXAM_SUPPLEMENT;
            } else {
                $state = SIGN_STATE_EXAM;
            }
        } else {
            $state = SIGN_STATE_EXAM;
        }

        // 刷脸签到必须传签到图片，刷卡签到可不传
        if($this->post("sign_image")){
            $imageBase64 = $this->post("sign_image", false);
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("签到失败，图片参数错误");
        }

        // 签到时间
        $signTime = $this->post("sign_time");
        if(!$signTime) throw new Exception("签到失败，签到时间不能为空");     
        // 如果是刷卡签到，获取学生信息
        if($signType == SIGN_TYPE_CARD) {
            $realcard = $this->post("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        } else {
            // 如果是人脸签到，获取学生信息
            $studentId = $this->post('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);  
        }

        if(!$studentInfo) throw new Exception("学生不存在");
        // 获取考试学生student_id数组
        $idArr = array();
        foreach($students as $student){
            $idArr[] = $student['userID'];
        }
        if(!in_array($studentInfo['id'], $idArr)){
            throw new Exception('该名学生不是该场考试成员');
        }
        // 写入图片
        $imageUrl = '';
        if(isset($imageBase64) && $imageBase64){
            // require_once('vendor/autoload.php');
            // $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".". $imageType;
            // $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            // $client = new Upyun\Upyun($serviceConfig);
            // $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
            // // 写文件上传调试日志
            // if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

            // $imageUrl = UP_URL . $fileName;

            $this->load->library('localUploader');
            $imageUrl = $this->localuploader->uploadBase64Image($imageBase64);
            if($imageUrl == false) {
                throw new Exception('系统错误，请联系管理员');
            }

        }
        if($this->post("sign_image_url")) {
            $imageUrl = $this->post("sign_image_url");
        }




        // 入库，做个毛线逻辑
        $insert['school_id'] = $studentInfo['school_id'];
        $insert['class_id'] = $studentInfo['class_id'];
        // 设置course_id为0
        $insert['course_id'] = 0;
        $insert['exam_room_id'] = $examRoomId;
        $insert['student_id'] = $studentInfo['id'];
        $insert['student_card_number'] = $studentInfo['realcard'];
        $insert['brand_id'] = $brandId;
        $insert['sign_type'] = $signType;
        $insert['state'] = $state;
        // 刷卡类型签到的图片路径设置为空
        // $insert['sign_img'] = isset($fileName) ? UP_URL . $fileName : '';
        $insert['sign_img'] = $imageUrl;

        $insert['sign_date'] = date("Y-m-d", strtotime($signTime));
        $insert['createtime'] = date("Y-m-d H:i:s", strtotime($signTime));
        $this->db->insert(ClassesModel::$signTable, $insert);

        // 返回值
        $ret['name'] = $studentInfo['realname'];
        $ret['signId'] = $this->db->insert_id();

        // 插入考勤临时表
        $this->db->insert(ClassesModel::$signTempTable, $insert);

        exit(json("", true, $ret));
    }

    // 获取考试考勤数据
    public function get_student_exam_sign_data($examRoomId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('dataModel');
        // 判断考试id是否存在
        if(empty($examRoomId)){
            throw new Exception('考场id不能为空');
        }
        $examRoom = $this->dataModel->get_exam_room_detail_info($examRoomId);
        if(null === $examRoom){
            throw new Exception('考场id无效');
        }
        $students = json_decode($examRoom['students'], true);

        // 准考证号列表
        $ticketArr = array();

        // 获取考试学生student_id数组
        $idArr = array();
        if($students) {
            $ticketArr = array_value_to_key($students, 'userID');

            foreach($students as $student){
                $idArr[] = $student['userID'];
            }
            // 考试学生student_id数组去重
            $idArr = array_unique($idArr);
        }
       
        // 获取已签到学生id数组
        $signParams['field'] = 'id, student_id';
        $signStudents = $this->dataModel->get_sign_exam_data($examRoomId, $signParams);
        $idSignArr = array();
        foreach($signStudents as $student){
            $idSignArr[] = $student['student_id'];
        }
        // 已签到学生id数组去重
        $idSignArr = array_unique($idSignArr);
        // 获取当场考试已签到学生数组
        $signIds = array();
        $notSignIds = array();
        foreach($idArr as $id){
            if(!empty($id)){
                if(in_array($id, $idSignArr)){
                    $signIds[] = $id;
                } else {
                    $notSignIds[] = $id;
                }
            }
        }

        // 获取已签到学生详情数据
        if(count($signIds) === 0){
            $ret['sign']['count'] = 0;
            $ret['sign']['data'] = [];
        } else {
            $ret['sign']['count'] = count($signIds);
            $signStudents = array();
            foreach($signIds as $key => $signId){
                $studentInfo = $this->schoolModel->get_student_info($signId);
                $params['student_id'] = $signId;
                $signInfos = $this->dataModel->get_sign_exam_data($examRoomId, $params);
                $signInfo = $signInfos[0];
                $signStudents[$key]['id'] = $signInfo['id'];
                $signStudents[$key]['studentId'] = $studentInfo['id'];
                $signStudents[$key]['studentCard'] = $studentInfo['realcard'];
                $signStudents[$key]['name'] = $studentInfo['realname'];
                $signStudents[$key]['image'] = $signInfo['sign_img'] . "!small";
                $signStudents[$key]['signTime'] = $signInfo['createtime'] ? date("H时i分", strtotime($signInfo['createtime'])) : '';
                $signStudents[$key]['signTimeDetail'] = $signInfo['createtime'] ? $signInfo['createtime'] : '';
                $signStudents[$key]['faceImage'] = $studentInfo['face_image'];
                $signStudents[$key]['headimgurl'] = $studentInfo['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');         
                $signStudents[$key]['temperature'] = "";
                $signStudents[$key]['studentTicket'] = isset($ticketArr[$studentInfo['id']]) ? $ticketArr[$studentInfo['id']]['studentTicket'] : '';
            }
            $ret['sign']['data'] = $signStudents;
        }
        // 获取未签到学生详情数据
        if(count($notSignIds) === 0){
            $ret['noSign']['count'] = 0;
            $ret['noSign']['data'] = [];
        } else {
            $ret['noSign']['count'] = count($notSignIds);
            $notSignStudents = array();
            foreach($notSignIds as $key => $notSignId){
                $studentInfo = $this->schoolModel->get_student_info($notSignId);
                $notSignStudents[$key]['id'] = NULL;
                $notSignStudents[$key]['studentId'] = $studentInfo['id'];
                $notSignStudents[$key]['studentCard'] = $studentInfo['realcard'];
                $notSignStudents[$key]['name'] = $studentInfo['realname'];
                $notSignStudents[$key]['image'] = "!small";
                $notSignStudents[$key]['signTime'] = '';
                $notSignStudents[$key]['faceImage'] = $studentInfo['face_image'];
                $notSignStudents[$key]['headimgurl'] = $studentInfo['gender'] == '男' ? get_sys_img('boy.jpg') : get_sys_img('girl.jpg');         
                $notSignStudents[$key]['studentTicket'] = isset($ticketArr[$studentInfo['id']]) ? $ticketArr[$studentInfo['id']]['studentTicket'] : '';
            }
            $ret['noSign']['data'] = $notSignStudents;
        }
        exit(json('', true, $ret));
    }

    // 学生选科
    public function get_subject_choice_report($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->get('cardnum')) && empty($this->get('id'))) {
            throw new Exception('参数不能为空');
        }
        if($this->get('cardnum')) {
            $student = $this->schoolModel->get_student_info_by_realcard($this->get('cardnum'), $brandInfo['school_id']);
        } else {
            $student = $this->schoolModel->get_student_info($this->get('id'));
        }
        if(empty($student)) {
            throw new Exception('无效的用户id或卡号');
        }
        $schoolId = $student['school_id'];
        $school = $this->schoolModel->get_school_info($schoolId);
        if(empty($school['school_from'])) {
            throw new Exception('该学生不是学校的');
        }
        $xStudentId = $student['x_student_id'];
        $schoolId = $school['school_x_id'];
        $loginId = $school['school_x_params'];
        $token = $school['school_x_token'];
        // 加载类库
        $this->load->library("haozhuanye");
        $result = $this->haozhuanye->get_subject_choice_report($schoolId, $loginId, $token, $xStudentId);
        if(!isset($result['status']) || $result['status'] !== 'success') {
            if(!isset($result['errorMessage'])) {
                $result['errorMessage'] = '接口报错';
            }
            throw new Exception($result['errorMessage']);
        }
        $url = $result['result'];
        header("Location: " . $url);
    }

    // 检查班牌是否在校
    public function check_brand_is_online($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        $isOnline = $brandInfo['is_online'] ? true : false;
        // var_export($info);exit;
        // 判断上线时间是否当天
        $today = date('Y-m-d') . " 00:00:00";
        if($brandInfo['online_time'] <  $today) {
            $isOnline = false;
        }
        exit(json('', true, array(
            'is_online' => $isOnline
        )));
    }

    // 获取班牌留言列表
    public function get_brand_note($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");

        $noteList = $this->wxUserModel->get_user_wx_note_list($studentInfo['id'], BIND_TYPE_STUDENT, 1);
        $filterdNoteList = array();
        $unreadArr = array();
        foreach($noteList as $note) {
            if($note['send_user_id'] === $note['receive_user_id']) {
                // 家长留言
                $otherUserId = $studentInfo['id'];
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['is_parent'] == 1) {
                    if(isset($unreadArr[$otherUserId])) {
                        $unreadArr[$otherUserId] ++;
                    } else {
                        $unreadArr[$otherUserId] = 1;
                    }
                }
            } else {
                // 教师留言
                if($note['send_user_type'] == BIND_TYPE_TEACHER) {
                    $otherUserId = $note['send_user_id'];
                } else {
                    $otherUserId = $note['receive_user_id'];
                }
                // 计算未读数
                if($note['has_read'] == 0 && $note['is_delete'] == 0 && $note['send_user_type'] == BIND_TYPE_TEACHER) {
                    if(isset($unreadArr[$otherUserId])) {
                        $unreadArr[$otherUserId] ++;
                    } else {
                        $unreadArr[$otherUserId] = 1;
                    }
                }
            }
            if(!isset($filterdNoteList[$otherUserId])) {
                $filterdNoteList[$otherUserId] = $note; 
            }
        }
        $resultArr = array();
        if($filterdNoteList) {
            foreach($filterdNoteList as $key => $value) {
                // 家长留言
                if($value['send_user_id'] === $value['receive_user_id']) {
                    // 获取学生信息
                    $student = $this->schoolModel->get_student_info($key);
                    // 获取姓名
                    $realname = $student['realname'];
                    // 获取头像
                    $headimgurl = $student['headimgurl'];
                    // 角色
                    $userType = '家长';  
                } else {
                    // 获取教师信息
                    $teacher = $this->schoolModel->get_school_user_info_realname($key);
                    // 获取姓名
                    $realname = $teacher['realname'];
                    // 获取头像
                    $headimgurl = $teacher['headimgurl'];
                    $userType = '教师';
                }
                $resultArr[] = array(
                    'other_user_id' => $key,
                    'other_user_type' => $userType,
                    'realname' => $realname,
                    'headimgurl' => $headimgurl,
                    // 时间去掉秒
                    'createtime' => time_remove_second($value['createtime']),
                    // 获取未读数
                    'unread_count' => isset($unreadArr[$key]) ? $unreadArr[$key] : 0,
                    'content_type' => $value['type'],
                    'content' => $value['type'] == WX_NOTE_TYPE_TEXT ? base64_decode($value['content']) : $value['content'],
                    'is_delete' => $value['is_delete']
                );
            }
        }
        exit(json('', true, $resultArr));
    }

    // 获取班牌留言对话框
    public function get_brand_note_dialog($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");
        // 对方用户信息
        $otherUserId = $this->get('other_user_id');
        $otherUserType = $this->get('other_user_type');
        if(empty($otherUserId) || empty($otherUserType)) {
            throw new Exception('参数错误');
        }
        if($otherUserType == '家长') {
            $otherUserType = BIND_TYPE_STUDENT;
        } elseif($otherUserType == '教师') {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            throw new Exception('"other_user_type"参数格式不正确');
        }
        // 获取对方头像
        if($otherUserType == BIND_TYPE_TEACHER) {
            // 获取教师信息
            $teacher = $this->schoolModel->get_school_user_info_realname($otherUserId);
            if(empty($teacher)) {
                throw new Exception('用户不存在');
            }
            // 获取头像
            $otherUserheadimgurl = $teacher['headimgurl'];
            // 获取姓名,添加后缀
            $otherUserRealname = $teacher['realname'] . '（教师）';
        } else {
            // 获取学生信息
            $student = $this->schoolModel->get_student_info($otherUserId);
            if(empty($student)) {
                throw new Exception('用户不存在');
            }
            // 获取头像
            $otherUserheadimgurl = $student['headimgurl'];
            // 获取姓名,添加后缀
            $otherUserRealname = $student['realname'] . '（家长）';
        }
        
        // 页码，每页50条，默认第一页
        $page = $this->get('page') ? $this->get('page') : 1;
        // 获取留言记录
        $noteArr = $this->wxUserModel->get_wx_note_dialog($studentInfo['id'], BIND_TYPE_STUDENT, $otherUserId, $otherUserType, 1, $page);
        $resultArr = array();
        if($noteArr) {
            // 颠倒顺序
            $noteArr = array_reverse($noteArr);
            foreach($noteArr as $note) {
                // 时间去掉秒
                $createtime = time_remove_second($note['createtime']);
                // 判断本人是否发送人
                if($otherUserType == BIND_TYPE_STUDENT) {
                    // 家长留言
                    $isSelf = $note['is_parent'] == 1 ? 0 : 1;
                } else {
                    // 教师留言
                    $isSelf = $note['send_user_id'] == $studentInfo['id'] ? 1 : 0;
                }

                // 设置头像
                $headimgurl = $isSelf ? $studentInfo['headimgurl'] : $otherUserheadimgurl;
                // 设置用户名
                $realname = $isSelf ? $studentInfo['realname'] : $otherUserRealname;
                if(empty($headimgurl)) {
                    // 若头像为空，设置默认头像
                    $headimgurl = get_sys_img('man.jpg');
                }
                // 判断是否2分钟内
                $twoMinAgo = date('Y-m-d H:i', time() - 120);
                if($note['createtime'] >= $twoMinAgo) {
                    $isCurrent = 1;
                } else {
                    $isCurrent = 0;
                }

                $resultArr[] = array(
                    'id' => $note['id'],
                    'is_self' => $isSelf,
                    'is_current' => $isCurrent,
                    'realname' => $realname,
                    'headimgurl' => $headimgurl,
                    // 时间去掉秒
                    'createtime' => $createtime,
                    'content_type' => $note['type'],
                    'content' => $note['type'] == WX_NOTE_TYPE_TEXT ? base64_decode($note['content']) : $note['content'],
                    'has_read' => $note['has_read'],
                    'is_delete' => $note['is_delete']
                );
            }
        }
        // 判断是否只有一页
        if(count($noteArr) == WX_NOTE_PAGE_SIZE) {
            $isOnlyOnePage = false;
        } else {
            $isOnlyOnePage = true;   
        }
        // 设置文字和图片为已读
        if($otherUserType == BIND_TYPE_TEACHER) {
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $studentInfo['id'],
                'send_user_id' => $otherUserId,
                'is_brand' => 1,
                'type' => WX_NOTE_TYPE_TEXT
            ));
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $studentInfo['id'],
                'send_user_id' => $otherUserId,
                'is_brand' => 1,
                'type' => WX_NOTE_TYPE_IMG
            ));
        } else {
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $studentInfo['id'],
                'send_user_id' => $studentInfo['id'],
                'is_brand' => 1,
                'is_parent' => 1,
                'type' => WX_NOTE_TYPE_TEXT
            ));
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $studentInfo['id'],
                'send_user_id' => $studentInfo['id'],
                'is_brand' => 1,
                'is_parent' => 1,
                'type' => WX_NOTE_TYPE_IMG
            ));
        }

        // 推送socket消息到移动端
        $this->load->library('socket');
        $channelId = $studentInfo['id'] . '_' . BIND_TYPE_STUDENT . '_' . $otherUserId;
        // $noteInfo = $this->wxUserModel->get_wx_note_info_by_user($studentInfo['id'], BIND_TYPE_STUDENT, $otherUserId, 1);
        // if($noteInfo) {
        //     $this->socket->send_note_msg_read($channelId, $noteInfo['id'], 1);
        // }
        $this->socket->send_note_msg_read($channelId, '', 1);

        exit(json('', true, $resultArr));
    }

    // 发送班牌留言
    public function send_brand_note($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->post('student_id') && null === $this->post('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->post("student_id")) {
            $studentId = $this->post("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);    
        } else {
            // 如果是传学生卡号
            if($this->post("cardnum")) {
                $realcard = $this->post("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");

        $content = trim($this->post('content'));
        $otherUserId = $this->post('other_user_id');
        $otherUserType = $this->post('other_user_type');
        if(empty($content)) {
            throw new Exception('内容不能为空');
        }
        if(empty($otherUserId)) {
            throw new Exception('other_user_id不能为空');
        }
        if($otherUserType == '家长') {
            $otherUserType = BIND_TYPE_STUDENT;
        } elseif($otherUserType == '教师') {
            $otherUserType = BIND_TYPE_TEACHER;
        } else {
            throw new Exception('other_user_type参数格式不正确');
        }
        $type = WX_NOTE_TYPE_TEXT;
        // 音频留言
        if($this->post('type') == WX_NOTE_TYPE_AUDIO) {
            // $content = trim($this->post('content', false));
            // // 写入音频
            // require_once('vendor/autoload.php');
            // $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".mp3";
            // $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            // $client = new Upyun\Upyun($serviceConfig);
            // $result = $client->write("/". $fileName, file_get_contents($content));   // 上传图片，自动创建目录
            // if(!isset($result['x-upyun-content-type']) || $result['x-upyun-content-type'] != 'audio/mp3') throw new Exception("音频格式要求是mp3");
            // $content = UP_URL. $fileName;
            // $type = WX_NOTE_TYPE_AUDIO;
        }
        // 入库
        $data['type'] = $type;
        $data['content'] =  $type == WX_NOTE_TYPE_TEXT ? base64_encode($content) : $content;
        $data['send_user_id'] = $studentInfo['id'];
        $data['send_user_type'] = BIND_TYPE_STUDENT;
        $data['receive_user_id'] = $otherUserId;
        $data['receive_user_type'] = $otherUserType;
        $data['is_brand'] = 1;
        $data['is_delete'] = 0;
        $data['is_parent'] = 0;
        $data['createtime'] = date('Y-m-d H:i:s');
        $data['updatetime'] = date('Y-m-d H:i:s');
        $this->db->insert(WxUserModel::$wxNoteTable, $data);
        // 须在这里定义，不然会被下面的影响到
        $id = $this->db->insert_id();
        if($type == WX_NOTE_TYPE_AUDIO) {
            $content = '[语音]';
        } elseif ($type == WX_NOTE_TYPE_IMG) {
            $content = '[图片]';
        }
        // 发送模板消息
        $url = wx_url('pub/note_dialog?send_user_id=' . $studentInfo['id'] . '&receive_user_id=' . $otherUserId .'&receive_user_type=' . $otherUserType . '&is_brand=1');
        $tempData = array(
            'keyword1' => array(
                'value' => $studentInfo['realname']
            ),
            'keyword2' => array(
                'value' => $data['createtime']
            ),
            'keyword3' => array(
                'value' => transformBrForNote($content)
            ),
        );
        $this->load->library('wxtemplate');
        $this->wxtemplate->send_template_msg_for_user($otherUserId, $otherUserType, WX_TEMPLATE_NOTE_PARENT, $tempData, $url);

        // 推送socket消息到移动端
        $this->load->library('socket');
        $channelId = $studentInfo['id'] . '_' . BIND_TYPE_STUDENT . '_' . $otherUserId;
        // 获取用户头像
        $headimgurl = $studentInfo['headimgurl'] ? $studentInfo['headimgurl'] : get_sys_img('man.jpg');
        $this->socket->send_note_msg($channelId, $id, $type, $content, $headimgurl, 1, time_remove_second($data['createtime']));
        // 发送给移动端留言列表页面
        $channelIdForList = $otherUserId . '_' . $otherUserType;
        $this->socket->send_note_msg_for_list($channelIdForList, $studentInfo['id'], transformBrForNote($content), 1, time_remove_second($data['createtime']));
        // 返回id，用于删除
        exit(json('发送成功', true, array(
            'id' => $id
        )));
    }

    // 撤回班牌留言
    public function delete_brand_note($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->post('student_id') && null === $this->post('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->post("student_id")) {
            $studentId = $this->post("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);    
        } else {
            // 如果是传学生卡号
            if($this->post("cardnum")) {
                $realcard = $this->post("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");

        $noteId = $this->post('note_id');
        $noteInfo = $this->wxUserModel->get_wx_note_info($noteId);
        if(empty($noteInfo)) {
            throw new Exception('note_id不存在');
        }
        if($noteInfo['is_brand'] == 0 || $noteInfo['send_user_id'] != $studentId) {
            throw new Exception('无删除权限');
        }
        $this->db->update(WxUserModel::$wxNoteTable, array(
            'is_delete' => 1,
            'updatetime' =>date('Y-m-d H:i:s')
        ), array('id' => $noteId));

        // 推送socket消息到移动端
        $this->load->library('socket');
        $channelId = $noteInfo['send_user_id'] . '_' . $noteInfo['send_user_type'] . '_' . $noteInfo['receive_user_id'];
        $this->socket->send_note_delete_msg($channelId, $noteInfo['id'], 1);
        // 发送给移动端留言列表页面
        $channelIdForList = $noteInfo['receive_user_id'] . '_' . $noteInfo['receive_user_type'];
        $this->socket->send_note_delete_msg_for_list($channelIdForList, $noteInfo['send_user_id'], 1, time_remove_second(date('Y-m-d H:i:s')));

        exit(json('删除成功', true));
    }

    // 获取家长和老师列表
    public function get_parent_and_teacher($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");
        $resultArr[] = array(
            'type' => '家长',
            'id' => $studentInfo['id'],
            'realname' => $studentInfo['realname'],
            'headimgurl' => $studentInfo['headimgurl'] ? $studentInfo['headimgurl'] : get_sys_img('man.jpg')
        );
        // 获取班级信息
        $classInfo = $this->classesModel->get_class_info($studentInfo['class_id']);
        if(empty($classInfo)) {
            exit(json('', true, $resultArr));
        }

        // 获取执教关系列表
        $coachParams['classId'] = $studentInfo['class_id'];
        $this->load->model('staffModel');
        $coachList = $this->staffModel->get_coach_list($coachParams);
        // 获取教师列表
        $teacherParams['isDelete'] = 0;
        $teacherParams['schoolId'] = $studentInfo['school_id'];
        $teacherList = $this->schoolModel->get_teacher_list($teacherParams);
        // 使用id作为键
        $teacherList = array_value_to_key($teacherList, 'id');
        $teacherArr = array();
        foreach($coachList as $coach) {
            $teacherId = $coach['teacher_id'];
            if(isset($teacherList[$teacherId]) && !in_array($teacherList[$teacherId], $teacherArr)) {
                array_push($teacherArr, $teacherList[$teacherId]);
            }
        }

        // $teachParams['isDelete'] = 0;
        // $teachParams['classId'] = $classInfo['id'];
        // $teacherList = $this->schoolModel->get_teacher_list($teachParams);
        foreach($teacherArr as $key => $teacher) {
            // 获取首字母
            $teacherArr[$key]['realnameFirstChar'] = getFirstChar($teacher['realname']);
        }
        // 按姓名首字母排序
        $timeKey =  array_column($teacherArr, 'realnameFirstChar');
        array_multisort($timeKey, SORT_ASC, $teacherArr);
        foreach($teacherArr as $teacher) {
            array_push($resultArr, array(
                'type' => '教师',
                'id' => $teacher['id'],
                'realname' => $teacher['realname'],
                'headimgurl' => $teacher['headimgurl'] ? $teacher['headimgurl'] : get_sys_img('man.jpg')
            ));
        }
        exit(json('', true, $resultArr));
    }

    // 设置消息为已读并发socket通知对方
    public function set_note_has_read($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        $noteId = $this->post('note_id');
        $isAudio = $this->post('is_audio');
        // var_export($isAudio);exit;
        if(empty($noteId) || $isAudio === NULL) {
            throw new Exception('参数错误');
        }
        // 获取留言详情
        $noteInfo = $this->wxUserModel->get_wx_note_info($noteId);
        if(empty($noteInfo)) {
            throw new Exception('参数错误');
        }
        // 推送socket消息到移动端
        $this->load->library('socket');
        $channelId = $noteInfo['receive_user_id'] . '_' . $noteInfo['receive_user_type'] . '_' . $noteInfo['send_user_id'];
        if($isAudio) {
            // 设置该音频已读
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'id' => $noteId
            ));
            $this->socket->send_note_msg_read_audio($channelId, $noteId, 1);
        } else {
            // 设置文字和图片为已读
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $noteInfo['receive_user_id'],
                'send_user_id' => $noteInfo['send_user_id'],
                'is_brand' => $noteInfo['is_brand'],
                'type' => WX_NOTE_TYPE_TEXT
            ));
            $this->db->update(WxUserModel::$wxNoteTable, array(
                'has_read' => 1,
                'updatetime' => date('Y-m-d H:i:s')
            ), array(
                'has_read' => 0,
                'receive_user_id' => $noteInfo['receive_user_id'],
                'send_user_id' => $noteInfo['send_user_id'],
                'is_brand' => $noteInfo['is_brand'],
                'type' => WX_NOTE_TYPE_IMG
            ));
            $this->socket->send_note_msg_read($channelId, $noteId, 1);
        }

        // $channelId = $noteInfo['send_user_id'] . '_' . $noteInfo['send_user_type'] . '_' .$noteInfo['receive_user_id'];
        exit(json('', true));
    }


    // 获取我的考勤
    public function get_student_attendance($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('wxUserModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("接口错误，不存在的学生ID");
        $studentId = $studentInfo['id'];
        // 设置ticket
        $ticket = md5(uniqid() . $studentId);
        // 入库
        $this->db->update(SchoolModel::$schoolStudentTable, array(
            'ticket' => $ticket,
            'updatetime' => date('Y-m-d H:i:s')
        ), array(
            'id' => $studentId
        ));
        $this->load->library('haozhuanye');
        $url = $this->haozhuanye->get_student_attendance_url() . $ticket;
        exit(json('', true, array(
            'url' => $url
        )));
    }

    // 获取学生成绩大项
    public function get_student_result_major_list($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        $this->load->model('dataModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if (null === $this->get('student_id') && null === $this->get('cardnum')) {
            throw new Exception("参数不能为空");
        }

        // 如果是传学生ID
        if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");
        $resultMajorList = $this->dataModel->get_result_list_by_student_id($studentInfo['id']);
        exit(json('', true, $resultMajorList));
    }

    // 获取学生成绩
    public function get_student_result($brandId) {
         // 加载数据库类
         $this->load->model('classesModel');
         $this->load->model('schoolModel');
         $this->load->model('dataModel');
         // 获取班牌信息
         $brandInfo = $this->classesModel->get_brand_info($brandId);
         if(!$brandInfo) exit(json("无效的班牌id", false));
         if (null === $this->get('student_id') && null === $this->get('cardnum')) {
             throw new Exception("参数不能为空");
         }

         // 如果是传学生ID
         if($this->get("student_id")) {
            $studentId = $this->get("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
            if(empty($studentInfo)) {
                throw new Exception('学生id不存在');
            }
            if($studentInfo['school_id'] != $brandInfo['school_id']) {
                throw new Exception('学生id不存在');
            }
        } else {
            // 如果是传学生卡号
            if($this->get("cardnum")) {
                $realcard = $this->get("cardnum");
                $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
            }
        }
        if(!$studentInfo) throw new Exception("学生id不存在");
        $majorId = $this->get('major_id');
        if(empty($majorId)) {
            throw new Exception('major_id参数不能为空');
        }
        $result = $this->dataModel->get_result_info_by_major_id($majorId, $studentInfo['id']);
        if($result) {
            // 处理value格式
            $valueArr = json_decode($result['value'], true);
            foreach($valueArr as $key => $item) {
                unset($valueArr[$key]['subject_id']);
            }
            // $resArr = array();
            // foreach($valueArr as $item) {
            //     $subjectName = $item['subject_name'];
            //     $score = $item['score'];
            //     array_push($resArr, $subjectName . '：' . $score);
            // }
            // $result['value'] = implode(', ', $resArr);
            $result['value'] = $valueArr;

            // 处理total格式
            if(strstr($result['total'], '.0')) {
                $result['total'] = explode('.', $result['total'])[0];
            }
            // 判断是否显示年级排名
            if($result['show_grade_rank']) {
                // 获取年级所有成绩
                $gradeResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($gradeResultList as $key => $item) {
                    $gradeResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($gradeResultList[$key]['total'] == $gradeResultList[$key - $i]['total']) {
                                $gradeResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                }
                // 用id作为键值
                $gradeResultList = array_value_to_key($gradeResultList, 'id');
                // 年级排名
                $result['grade_rank'] = $gradeResultList[$result['id']]['rank'];
            }
            // 判断是否显示班级排名
            if($result['show_class_rank']) {
                // 获取年级所有成绩
                $classResultList = $this->dataModel->get_result_list(array(
                    'resultGradeId' => $result['result_grade_id'],
                    'classId' => $result['class_id'],
                    'isDelete' => 0,
                    'orderBy' => '`total` DESC'
                ));
                foreach($classResultList as $key => $item) {
                    $classResultList[$key]['rank'] = $key + 1;
                    // 处理并列排名问题
                    $loop = true;
                    $i = 1;
                    while($loop) {
                        if($key - $i >= 0) {
                            if($classResultList[$key]['total'] == $classResultList[$key - $i]['total']) {
                                $classResultList[$key]['rank'] --;
                                $i++;
                            } else {
                                $loop = false;
                            }
                        } else {
                            $loop = false;
                        }
                    }
                }
                // 用id作为键值
                $classResultList = array_value_to_key($classResultList, 'id');
                // 班级排名
                $result['class_rank'] = $classResultList[$result['id']]['rank'];
            }
            unset($result['show_grade_rank']);
            unset($result['show_class_rank']);
            unset($result['updatetime']);
            unset($result['is_delete']);
            unset($result['result_grade_id']);
        }
        exit(json('', true, $result));
    }

    // 获取外部链接
    public function get_custom_menu_list($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        $schoolId = $brandInfo['school_id'];
        // 获取外部链接
        $data['schoolId'] = $schoolId;
        $data['position'] = CUSTOM_MENU_POSITION_BRAND;
        $data['field'] = 'id, title, icon, link, mode';
        $menuList = $this->schoolModel->get_custom_menu_list($data);
 
       exit(json('', true, $menuList));
   }

    // 学生德育评价
    public function get_student_moral_remark($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->get('cardnum')) && empty($this->get('student_id'))) {
            throw new Exception('参数不能为空');
        }
        if($this->get('student_id')) {
            $student = $this->schoolModel->get_student_info($this->get('student_id'));
        } else {
            $student = $this->schoolModel->get_student_info_by_realcard($this->get('cardnum'), $brandInfo['school_id']);
        }
        if(empty($student)) {
            throw new Exception('无效的卡号');
        }
        if($student['school_id'] != $brandInfo['school_id']) {
            throw new Exception('学生id不存在');
        }
        $params['studentId'] = $student['id'];
        $params['schoolId'] = $brandInfo['school_id'];
        $params['campusId'] = $brandInfo['campus_id'];
        $params['isDelete'] = 0;
        $remarkList = $this->contentModel->get_moral_remark_list($params);
        foreach($remarkList as &$remark) {
            $result = $this->contentModel->get_moral_remark_result_info($remark['result_id']);
            $remark['result'] = $result['title'];
        }
        exit(json('', true, $remarkList));
    }

    // 学生德育活动
    public function get_student_moral_activity($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->get('cardnum')) && empty($this->get('student_id'))) {
            throw new Exception('参数不能为空');
        }
        if($this->get('student_id')) {
            $student = $this->schoolModel->get_student_info($this->get('student_id'));
        } else {
            $student = $this->schoolModel->get_student_info_by_realcard($this->get('cardnum'), $brandInfo['school_id']);
        }
        if(empty($student)) {
            throw new Exception('无效的卡号');
        }
        if($student['school_id'] != $brandInfo['school_id']) {
            throw new Exception('学生id不存在');
        }
        if($this->get('pending') == 1) {
            $params['state'] = MORAL_PENDING;
        }
        if($this->get('exclude_pending') == 1) {
            $params['excludePending'] = MORAL_PENDING;
        }

        $params['studentId'] = $student['id'];
        $params['schoolId'] = $brandInfo['school_id'];
        $params['campusId'] = $brandInfo['campus_id'];
        $params['isDelete'] = 0;
        $activityList = $this->contentModel->get_moral_activity_list($params);
        foreach($activityList as &$activity) {
            $activity['state'] = transform_activity_state_to_chinese($activity['state']);
            // 获取评价老师名称
            if($activity['remark_user_id']) {
                $teacher = $this->schoolModel->get_teacher_info($activity['remark_user_id']);
                $activity['remark_teacher_realname'] = $teacher['realname'];
            }
        }
        exit(json('', true, $activityList));
    }

    // 学校德育动态栏目列表
    public function get_moral_timeline_subject($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        $params['schoolId'] = $brandInfo['school_id'];
        $params['campusId'] = $brandInfo['campus_id'];
        $params['isDelete'] = 0;
        $subjectList = $this->contentModel->get_moral_timeline_subject_list($params);
        exit(json('', true, $subjectList));
    }

    // 学校德育动态
    public function get_moral_timeline($brandId, $page=1) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if($this->get('subject_id')) {
            $params['subjectId'] = $totalParams['subjectId'] = $this->get('subject_id');
        }
        $subjectParams['schoolId'] = $brandInfo['school_id'];
        $subjectParams['campusId'] = $brandInfo['campus_id'];
        $subjectParams['isDelete'] = 0;
        $subjectList = $this->contentModel->get_moral_timeline_subject_list($subjectParams);
        $subjectList = array_value_to_key($subjectList, 'id');

        // 获取数据条数
        $totalParams['schoolId'] = $brandInfo['school_id'];
        $totalParams['campusId'] = $brandInfo['campus_id'];
        $totalParams['isDelete'] = 0;
        $totalParams['getRowNumber'] = true;
        $total = $this->contentModel->get_moral_timeline_list($totalParams);

        $params['pageStart'] = ($page - 1) * ADMIN_PAGE_SIZE;
        $params['pageSize']= ADMIN_PAGE_SIZE;
        $params['schoolId'] = $brandInfo['school_id'];
        $params['campusId'] = $brandInfo['campus_id'];
        $params['isDelete'] = 0;
        $timelineList = $this->contentModel->get_moral_timeline_list($params);
        foreach($timelineList as &$timeline) {
            // 获取栏目名称
            $timeline['subject_title'] = $subjectList[$timeline['subject_id']]['title'];
        }
        $ret['total'] = $total;
        $ret['data'] = $timelineList;
        exit(json('', true, $ret));
    }

    // 获取设备CDKEY
    public function get_brand_cdkey(){
        // 加载数据库类
        $this->load->model('classesModel');
        // 获取设备物理地址
        $macAddress = $this->get("mac");
        if(!$macAddress) throw new Exception("参数错误");
        // 获取班牌ID
        $brandId = $this->get("id");
        // 激活码
        $cdKey = "";
        // 查询mac地址是否存在
        $macInfo = $this->classesModel->check_brand_mac($macAddress);
        if($macInfo) {
            $cdKey = $macInfo['cdkey'];

            // 如果时间超过2小时，则更新数据。
            // 方便后期维护
            if(!$cdKey && time() - strtotime($macInfo['createtime']) > (60 * 60 * 2)) {
                // 更新班牌ID
                $update['brand_id'] = $brandId;
                $update['createtime'] = date("Y-m-d H:i:s");
                $this->db->update(ClassesModel::$brandCdkeyTable, $update, "id='{$macInfo['id']}'");
            }

        } else {
            // 入库新纪录
            $insert['brand_id'] = $brandId ? $brandId : 0;
            $insert['mac_address'] = $macAddress;
            $insert['createtime'] = date("Y-m-d H:i:s");
            $this->db->insert(ClassesModel::$brandCdkeyTable, $insert);
        }

        exit(json("", true, $cdKey));
    }

    // 删除学生头像
    public function delete_student_face_image($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        // 如果是传学生ID
        if($this->post("student_id")) {
            $studentId = $this->post("student_id");
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            // 获取学生信息
            $cardNum = $this->post("cardnum");
            if(!$cardNum) throw new Exception("参数错误");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($cardNum, $brandInfo['school_id']);
        }
        if(empty($studentInfo)) {
            throw new Exception('参数错误');
        }
        if($studentInfo['school_id'] != $brandInfo['school_id']) {
            throw new Exception('参数错误');
        }
       
        $this->db->update(SchoolModel::$schoolStudentTable, array(
            'face_image' => '',
            'updatetime' => date('Y-m-d H:i:s')
        ), "id='{$studentInfo['id']}'");

        if($studentInfo['face_image']) {
            // 插入闸机任务
            $gateParams['schoolId'] = $brandInfo['school_id'];
            $gateParams['campusId'] = $brandInfo['campus_id'];
            // 过滤软删除
            $gateParams['isDelete'] = 0;
            $gateList = $this->schoolModel->get_gate_list($gateParams);
            if($gateList) {
                $insertTaskBatch = array();
                foreach($gateList as $gate) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $brandInfo['school_id'],
                        'campus_id' => $brandInfo['campus_id'],
                        'gate_id' => $gate['id'],
                        'device_sn' => $gate['device_sn'],
                        'user_id' => $studentInfo['id'],
                        'user_name' => $studentInfo['realname'],
                        'user_face_image' => $studentInfo['face_image'],
                        'user_type' => GATE_USER_TYPE_STUDENT,
                        'task_type' => GATE_TASK_TYPE_DELETE,
                        'task_state' => GATE_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(SchoolModel::$gateTaskTable, $insertTaskBatch);
                }
            }

            // 插入一体机任务
            $this->load->model('aioModel');
            $aioParams['schoolId'] = $brandInfo['school_id'];
            $aioParams['campusId'] = $brandInfo['campus_id'];
            // 过滤软删除
            $aioParams['isDelete'] = 0;
            $aioList = $this->aioModel->get_aio_list($aioParams);
            if($aioList) {
                $insertTaskBatch = array();
                foreach($aioList as $aio) {
                    array_push($insertTaskBatch, array(
                        'school_id' => $brandInfo['school_id'],
                        'campus_id' => $brandInfo['campus_id'],
                        'aio_id' => $aio['id'],
                        'facesluice_id' => $aio['facesluice_id'],
                        'user_id' => $studentInfo['id'],
                        'user_name' => $studentInfo['realname'],
                        'user_face_image' => $studentInfo['face_image'],
                        'user_type' => AIO_USER_TYPE_STUDENT,
                        'task_type' => AIO_TASK_TYPE_DELETE,
                        'task_state' => AIO_TASK_STATE_NEW,
                        'createtime' => date('Y-m-d H:i:s'),
                        'updatetime' => date('Y-m-d H:i:s')
                    ));
                }
                if($insertTaskBatch) {
                    $this->db->insert_batch(AioModel::$aioTaskTable, $insertTaskBatch);
                }
            }
        }

        exit(json("", true));
    }

    // 获取智能门锁信息
    public function get_smart_lock_info($brandId) {
        // 加载数据库类
        $this->load->model('classesModel');
        $this->load->model('schoolModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
       
        $data['schoolId'] = $brandInfo['school_id'];
        $data['campusId'] = $brandInfo['campus_id'];
        $data['classId'] = $brandInfo['class_id'];
        $data['isDelete'] = 0;
        $arr = $this->schoolModel->get_smart_lock_list($data);
        if($arr) {
            $res = $arr[0];
            exit(json('', true, $res));
        } else {
            exit(json('', false, NULL));
        }
   }

    // 判断开锁权限
    public function verify_unlock($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        
        // 获取学生信息
        if($this->post('student_id')) {
            $studentId = $this->post('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            $realcard = $this->post("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        }
        if(!$studentInfo) throw new Exception("签到失败，找不到对应的学生");

        // 获取门锁设备
        $deviceId = trim($this->post("device_id"));
        if(empty($deviceId)) {
            throw new Exception('参数错误');
        }
        $smartLockInfo = $this->schoolModel->get_smart_lock_info_by_device_id($brandInfo['school_id'], $brandInfo['campus_id'], $deviceId);
        if(empty($smartLockInfo)) {
            throw new Exception('设备id不存在');
        }
        // 判断白名单
        $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentInfo['id']);
        if(empty($whiteListInfo)) {
            throw new Exception('没有开锁权限');
        }

        exit(json("开锁权限正常", true));
    }

    // 判断开锁权限并返回门锁参数（合并上面获取门锁接口和判断权限两个接口）
    public function get_smart_lock_params($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");

        // 获取门锁信息
        $data['schoolId'] = $brandInfo['school_id'];
        $data['campusId'] = $brandInfo['campus_id'];
        $data['classId'] = $brandInfo['class_id'];
        $data['isDelete'] = 0;
        $arr = $this->schoolModel->get_smart_lock_list($data);
        if(empty($arr)) {
            throw new Exception('获取不到门锁设备信息');
        }
        // 获取第一个
        $smartLockInfo = $arr[0];
        
        // 获取学生信息
        if(empty($this->get('student_id')) && empty($this->get('cardnum'))) throw new Exception("参数错误");
        if($this->get('student_id')) {
            $studentId = $this->get('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            $realcard = $this->get("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        }
        if(!$studentInfo) throw new Exception("开锁失败，找不到对应的学生");
        
        // 判断白名单
        $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentInfo['id']);
        if(empty($whiteListInfo)) {
            throw new Exception('没有开锁权限');
        }
        exit(json("开锁权限正常", true, $smartLockInfo));
    }

    // 开锁接口
    public function unlock($brandId){
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');

        // 签到图片，base64与url二选一
        $imageBase64 = $this->post("sign_image", false);
        $imageUrl = $this->post("sign_image_url");
        if(empty($imageBase64) && empty($imageUrl)) {
            throw new Exception('图片参数不能为空');
        }
        if($imageBase64 && $imageUrl) {
            throw new Exception('图片参数错误');
        }
        if($imageBase64) {
            $imageType = get_img_type_from_base64($imageBase64);
            if(!$imageType) throw new Exception("签到失败，图片参数错误");
        }

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) throw new Exception("签到失败，找不到对应的班牌");
        
        // 获取学生信息
        if($this->post('student_id')) {
            $studentId = $this->post('student_id');
            $studentInfo = $this->schoolModel->get_student_info($studentId);
        } else {
            $realcard = $this->post("cardnum");
            $studentInfo = $this->schoolModel->get_student_info_by_realcard($realcard, $brandInfo['school_id']);
        }
        if(!$studentInfo) throw new Exception("签到失败，找不到对应的学生");

        // 获取门锁设备
        $deviceId = trim($this->post("device_id"));
        if(empty($deviceId)) {
            throw new Exception('参数错误');
        }
        $smartLockInfo = $this->schoolModel->get_smart_lock_info_by_device_id($brandInfo['school_id'], $brandInfo['campus_id'], $deviceId);
        if(empty($smartLockInfo)) {
            throw new Exception('设备id不存在');
        }
        // 判断白名单
        $whiteListInfo = $this->schoolModel->get_smart_lock_student_white_list_info_by_student_id($studentInfo['id']);
        if(empty($whiteListInfo)) {
            throw new Exception('没有开锁权限');
        }
        // 判断1分钟内是否有重复提交
        $recordParams['studentId'] = $studentInfo['id'];
        $recordParams['createtime'] = date("Y-m-d H:i:s");
        $recordParams['smartLockId'] = $smartLockInfo['id'];
        $recordList = $this->schoolModel->get_smart_lock_unlock_record_list($recordParams);
        if($recordList) {
            // // 测试服不限制
            // if(ENV != 'test' && ENV != 'local') {
                exit(json('1秒钟内不能重复提交', true));
            // }
        }

        if($imageBase64) {
            // // base64
            // // 写入图片
            // require_once('vendor/autoload.php');
            // $fileName = date("Y"). "/". date("m"). "/". date("d"). "/". time(). mt_rand(1000,10000) . ".". $imageType;
            // $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
            // $client = new Upyun\Upyun($serviceConfig);
            // $signImg = UP_URL. $fileName;
            // try{
            //     $result = $client->write("/". $fileName, file_get_contents($imageBase64));   // 上传图片，自动创建目录
            // } catch(Exception $e) {
            //     // 捕获同个图片名，上传多次报错
            //     throw new Exception("429 Too Many Requests");
            // }
    
            // // 写文件上传调试日志
            // if(!isset($result['x-upyun-width'])) throw new Exception("更新失败，图片参数错误");

            $this->load->library('localUploader');
            $signImg = $this->localuploader->uploadBase64Image($imageBase64);
            if($signImg == false) {
                throw new Exception('系统错误，请联系管理员');
            }
        } else {
            // 图片url
            $signImg = $imageUrl;
        }

        // 入库，做个毛线逻辑
        $insert['school_id'] = $studentInfo['school_id'];
        $insert['campus_id'] = $studentInfo['campus_id'];
        $insert['class_id'] = $studentInfo['class_id'];
        $insert['student_id'] = $studentInfo['id'];
        $insert['brand_id'] = $brandInfo['id'];
        $insert['scene_img'] = $signImg;
        $insert['smart_lock_id'] = $smartLockInfo['id'];
        $insert['device_id'] = $deviceId;
        $insert['createtime'] = date("Y-m-d H:i:s");
        $this->db->insert(SchoolModel::$smartLockUnlockRecordTable, $insert);
        // 返回值
        $ret['name'] = $studentInfo['realname'];
        $ret['unlockRecordId'] = $this->db->insert_id();

        exit(json("", true, $ret));
    }

    // 获取学生通讯录
    public function get_student_phone_book($brandId) {
        // 加载数据库类
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo) exit(json("无效的班牌id", false));
        if(empty($this->get('cardnum')) && empty($this->get('student_id'))) {
            throw new Exception('参数不能为空');
        }
        if($this->get('student_id')) {
            $student = $this->schoolModel->get_student_info($this->get('student_id'));
        } else {
            $student = $this->schoolModel->get_student_info_by_realcard($this->get('cardnum'), $brandInfo['school_id']);
        }
        if(empty($student)) {
            throw new Exception('学生不存在');
        }
        if($student['school_id'] != $brandInfo['school_id']) {
            throw new Exception('学生不存在');
        }
        $params['studentId'] = $student['id'];
        $params['schoolId'] = $brandInfo['school_id'];
        $params['campusId'] = $brandInfo['campus_id'];
        $params['isDelete'] = 0;
        $params['field'] = 'id, student_id, nickname, headimgurl, mobile';
        $list = $this->contentModel->get_phone_book_list($params);
       
        exit(json('', true, $list));
    }
}
